<script type="text/javascript">
    function zamanPlaceDeliveryOrder(orderId, name, phone, apartment, floor, building, sector, street, postcode, area, city, region, country, deliveryTime, convertTo, changePriceTo) {
        $('#placeOrderTypeBlock').hide();
        zamanEposPopupcloser();
        clearEposWorkArea();
        clearEposWorkAreaForOrderList();
        $('#categoryBreadcurm').show();
        $('#eposCategoryMenuList').show();
        $('#categoryBreadcurm').show();
        $('.breadcurmb-category').text('<?php echo sprintf($this->lang->line('placing_order_head'), $this->lang->line('delivery')) ?>');
        $('.breadcurmb-menu').show().text('');
        var html = `
        <div class="customer-search-box" id="deliveryCustomerSearchBox" style="padding-bottom:40px;background:transparent;">
            <div class="search-input"><input style="border-radius:0px;" placeholder="search postcode / phone" type="search" class="form-control text-uppercase" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" id="deliveryOrderInfoCollectFormSearch"></div>
            <div class="search-btn" onclick=getDeliveryCustomerByPhone()><span class="btn-primary-custom-1" style="padding: 10px 1px; height:31px; text-align:center; width:100%"><i class='icon icon-phone' style="color:#ffffff;"></i>&nbsp;<i class='icon icon-search' style="color:#ffffff;"></i></span></div>
        </div>
        <div class="page-loader" style="display: none;"></div>
        <form id="deliveryOrderInfoCollectForm">
            <div class="neworder-waiting ">
                <div class="delivery-field one-fifth truned-one-third ">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('customer_name') ?></label>
                        <input type="text" name="name" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" id='deliveryCustomerName' class="form-control text-capitalize" placeholder="<?php echo $this->lang->line('customer_name') ?>">
                        <input type="hidden" id="existingDeliveryCustomerName">
                        <input type="hidden" id="existingDeliveryCustomerPhone">
                        <input type="hidden" id="deliveryOrderId">
                        <input type="hidden" id="isConvertedToDelivery">
                        <input type="hidden" id="isConvertedToDeliveryPrice">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('customer_phone') ?></label>
                        <input type="text" onfocus="ShowPhonePad()" name="phone" id='deliveryCustomerPhone' class="form-control" placeholder="<?php echo $this->lang->line('customer_phone') ?>">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('house_info') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="building" id="deliveryCustomerBuilding" class="form-control" placeholder="<?php echo $this->lang->line('house_info') ?>">
                    </div>
                </div>
                <input type="hidden" name="floor" id="deliveryCustomerFloor" class="form-control" value=''>               
                <input type="hidden" name="apartment" id="deliveryCustomerApartment" class="form-control" value=''> 
                <input type="hidden" name="area" id="deliveryCustomerArea" class="form-control" value=''>                
                 <!--               
                 <div class="delivery-field one-fifth truned-one-third" style="display:none">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('floor') ?></label>
                        <input type="hidden" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="floor" id="deliveryCustomerFloor" class="form-control" placeholder="<?php echo $this->lang->line('floor') ?>">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third" style="display:none">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('apartment') ?></label>
                        <input type="hidden" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="apartment" id="deliveryCustomerApartment" class="form-control" placeholder="<?php echo $this->lang->line('apartment') ?>">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third" id="areaBlock" style="display:none;">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('area') ?></label>
                        <select class="form-control" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="area" id="deliveryCustomerArea"></select>
                    </div>
                </div>               
                 !-->                       
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('sector_word_street') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="sector" id='deliveryCustomerRoadNumber' class="form-control" placeholder="<?php echo $this->lang->line('sector_word_street') ?>">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('street_address') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="street" id='deliveryCustomerStreet'  class="form-control" placeholder="<?php echo $this->lang->line('street_address') ?>">
                    </div>
                    <div class="clearfix"></div>
                </div>
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('postcode') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="postcode" id='deliveryCustomerPostcode' class="form-control text-uppercase" placeholder="<?php echo $this->lang->line('postcode') ?>">
                    </div>
                </div>

                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('city') ?></label>
                        <input type="text" onfocus="setTargetKeyboard('keyboard-fixed-orderpage','setting-pagination-keyboard')" name="city" id='deliveryCustomerCity' class="form-control" placeholder="<?php echo $this->lang->line('city') ?>">
                    </div>
                </div>
                <input type="hidden" name="region"  id='deliveryCustomerRegion'/>              
                <input type="hidden" name="country"  id='deliveryCustomerCountry'/>               
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                        <label><?php echo $this->lang->line('extra_time') ?>(mins)</label>
                        <input type="text" onfocus="showTimeNumpad()" name="extra_time" id='deliveryExtraTime' class="form-control" placeholder="<?php echo $this->lang->line('extra_time') ?>(mins)">
                    </div>
                </div>
                <div class="delivery-field one-fifth truned-one-third">
                    <div class="form-group">
                       <label>&nbsp;</label>         
                       <div class='tab-group'><div onclick="clearDeliveryForm()"  class="tab-item" style="border-radius:3px; padding:9px 0px;"><?php echo $this->lang->line('clear_form') ?></div></div>
                    </div>
                </div>                
            </div>
            <div class="clearfix"></div>
            <div class="tab-group config-submit" style="padding:0px 10px">
                <button type="submit" onclick="initiateDeliveryOrder('deliveryOrderInfoCollectForm')"><span class="icon icon-folder"></span>&nbsp;<?php echo $this->lang->line('go') ?></button>
            </div>
            <div style="padding:3px 10px; display:none;" class="commonPhonePadForCustomer">
                <div style="border-radius:3px;"> 
                    <div class="tab-group keypad">
                      <div class="tab-item zaman-epos-nav quantity-digit keypad-key" style="background:none;padding:0px;"><?php echo $this->lang->line('phone_pad') ?></div>         
                    </div>
                   <div class="tab-group keypad">                     
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">1</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">2</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">3</div>               
                   </div>
                     <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">4</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">5</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">6</div>         
                    </div>            
                   <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">7</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">8</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">9</div>                      
                   </div> 
                    <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryActionKey">DEL</div> 
                        <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryNumKey">0</div>                     
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticPrimaryActionKey">CLR</div>        
                    </div>             
                </div>                         
            </div>
            <div style="padding:3px 10px; display:none;" class="deliveryExtraTimePad">
                <div style="border-radius:3px;"> 
                    <div class="tab-group keypad">
                        <div class="tab-item zaman-epos-nav quantity-digit keypad-key" style="background:none;padding:0px;"><?php echo $this->lang->line('extra_time') ?></div>
                    </div>
                   <div class="tab-group keypad">                     
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">5</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">10</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">15</div>  
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">20</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">25</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryActionKey">DEL</div>                 
                   </div>
                   <div class="tab-group keypad">
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">30</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">35</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">40</div>
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">45</div> 
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryNumKey">50</div>                     
                       <div class="tab-item zaman-epos-nav quantity-digit keypad-key DeliveryStaticExtraTimePrimaryActionKey">CLR</div>                       
                   </div> 
                </div>                         
            </div>                        
        </form>`;
        $('#eposCategoryMenuList').html(html);
        var userData = zamanEposCart.getUserData();
        var userApps = userData.userApps;
        var preveleges = userApps.length;
        if (preveleges > 1) {
            playBeepSound();
        }
        $("input#deliveryOrderInfoCollectFormSearch").suggest({
            label: "Formatted address",
            street_number_input: {
                id: "deliveryCustomerRoadNumber",
                label: "Road/Sector"
            },
            street_name_input: {
                id: "deliveryCustomerStreet",
                label: "Street"
            },
            zip_input: {
                id: "deliveryCustomerPostcode",
                label: "Postcode"
            },
            town_input: {
                id: "deliveryCustomerArea",
                label: "Town"
            },
            department_input: {
                id: "deliveryCustomerCity",
                label: "City"
            },
            region_input: {
                id: "deliveryCustomerRegion",
                label: "Region"
            },
            country_input: {
                id: "deliveryCustomerCountry",
                label: "Country"
            }
        });
        zamanPrimaryNumpad('deliveryCustomerPhone', 'DeliveryStaticPrimaryNumKey', 'DeliveryStaticPrimaryActionKey');
        zamanSecondaryNumpad('deliveryExtraTime', 'DeliveryStaticExtraTimePrimaryNumKey', 'DeliveryStaticExtraTimePrimaryActionKey');
        if (orderId > 0) {
            $('#deliveryOrderId').val(orderId);
            $('#deliveryCustomerName').val(name);
            $('#deliveryCustomerPhone').val(phone);
            $('#deliveryCustomerBuilding').val(building);
            $('#deliveryCustomerFloor').val(floor);
            $('#deliveryCustomerApartment').val(apartment);
            $('#deliveryCustomerRoadNumber').val(sector);
            $('#deliveryCustomerStreet').val(street);
            $('#deliveryCustomerPostcode').val(postcode);
            $('#deliveryCustomerArea').val(area);
            $('#deliveryCustomerCity').val(city);
            $('#deliveryCustomerRegion').val(region);
            $('#deliveryCustomerCountry').val(country);
            $('#existingDeliveryCustomerName').val(name);
            $('#existingDeliveryCustomerPhone').val(phone);
            var delTime = $('#deliveryExtraTime').val(deliveryTime).val();
            if ($.trim(delTime)) {
                $('#deliveryExtraTime').val(deliveryTime).attr('disabled', 'disabled');
            } else {
                $('#deliveryExtraTime').removeAttr('disabled');
            }
            $('#isConvertedToDelivery').val(convertTo);
            $('#isConvertedToDeliveryPrice').val(changePriceTo);
        } else {
            $('#deliveryExtraTime').removeAttr('disabled');
            if ($.trim(phone)) {
                zamanEposDb.epos_customer.get({'phone': phone}).then(function (aCustomer) {
                    if (typeof (aCustomer) !== 'undefined') {
                        zamanEposDb.epos_customer_address.get({lcid: aCustomer.lid}).then(function (aCustomerAddress) {
                            if (typeof (aCustomerAddress) !== 'undefined') {
                                $('#deliveryCustomerName').val(aCustomerAddress.name);
                                $('#deliveryCustomerPhone').val(aCustomerAddress.phone);
                                $('#deliveryCustomerBuilding').val(aCustomerAddress.building);
                                $('#deliveryCustomerFloor').val(aCustomerAddress.floor);
                                $('#deliveryCustomerApartment').val(aCustomerAddress.apartment);
                                $('#deliveryCustomerRoadNumber').val(aCustomerAddress.sector);
                                $('#deliveryCustomerStreet').val(aCustomerAddress.street);
                                $('#deliveryCustomerPostcode').val(aCustomerAddress.postcode);
                                $('#deliveryCustomerArea').val(area);
                                $('#deliveryCustomerCity').val(aCustomerAddress.city);
                                $('#deliveryCustomerRegion').val(aCustomerAddress.region);
                                $('#deliveryCustomerCountry').val(aCustomerAddress.country);
                            } else {
                                $('#deliveryCustomerName').val(aCustomer.name);
                                $('#deliveryCustomerPhone').val(aCustomer.phone);
                            }
                        });
                    } else {
                        $('#deliveryCustomerName').val(name);
                        $('#deliveryCustomerPhone').val(phone);
                    }
                });
            }
        }

    }

    function clearDeliveryForm() {
        $('#deliveryOrderInfoCollectFormSearch').val('');
        resetForm('deliveryOrderInfoCollectForm');
    }
    function getDeliveryCustomerByPhone() {
        var phone = $('#deliveryOrderInfoCollectFormSearch').val();
        zamanEposDb.epos_customer.get({phone: phone}).then(function (aCustomer) {
            if (typeof (aCustomer) !== 'undefined') {
                $('#deliveryCustomerName').val(aCustomer.name);
                $('#deliveryCustomerPhone').val(aCustomer.phone);
                zamanEposDb.epos_customer_address.get({lcid: aCustomer.lid}).then(function (aCustomerAddress) {
                    if (typeof (aCustomerAddress) !== 'undefined') {
                        $('#deliveryCustomerBuilding').val(aCustomerAddress.building);
                        $('#deliveryCustomerFloor').val(aCustomerAddress.floor);
                        $('#deliveryCustomerApartment').val(aCustomerAddress.apartment);
                        $('#deliveryCustomerRoadNumber').val(aCustomerAddress.sector);
                        $('#deliveryCustomerStreet').val(aCustomerAddress.street);
                        $('#deliveryCustomerPostcode').val(aCustomerAddress.postcode);
                        $('#deliveryCustomerArea').val(aCustomerAddress.area);
                        $('#deliveryCustomerCity').val(aCustomerAddress.city);
                        $('#deliveryCustomerRegion').val(aCustomerAddress.region);
                        $('#deliveryCustomerCountry').val(aCustomerAddress.country);
                    }
                });
            } else {
                warning('<?php echo $this->lang->line('warning') ?>', '<?php echo sprintf($this->lang->line('not_found'), $this->lang->line('customer')) ?>', '<?php echo $this->lang->line('close') ?>');
            }
        });
    }
    function initiateDeliveryOrder(formId) {
        $('#' + formId).validate({
            submitHandler: function () {
                $('.page-loader').show();
                var postcode = $('#deliveryCustomerPostcode').val();
                var area = $('#deliveryCustomerArea').val();
                var formattedPostCode = formatPostcode(postcode);
                var actualArea = null;
                if (formattedPostCode) {
                    var broken = formattedPostCode.split(' ');
                    var outward = broken[0];
                    var inward = parseInt(broken[1]);
                    var sector = parseInt(inward);
                    actualArea = outward + ' ' + Number(sector);
                } else {
                    actualArea = area;
                }
                if (actualArea !== null) {
                    zamanEposDb.epos_deliveryplan.get({'area': actualArea, 'status': '3'}).then(function (aplan) {
                        if (typeof (aplan) !== 'undefined') {
                            preCheckDeliveryPlan(actualArea, Number(aplan.delivery_charge), Number(aplan.min_order), Number(aplan.waiting_time));
                        } else {
                            warningForPreCheckDeliveryPlan(actualArea);
                        }
                    });
                }
            },
            errorClass: "has-error",
            highlight: function (e) {
                $(e).closest('.form-group').addClass('has-error');
                $.colorbox.resize();
            },
            unhighlight: function (e) {
                $(e).closest('.form-group').removeClass('has-error');
                $.colorbox.resize();
            },
            rules: {
                name: {required: true},
                phone: {phone: true, required: true},
                postcode: {required: true},
                street: {required: true},
                extra_time: {number: true, min: 1, max: 50}
            },
            messages: {
                name: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('name')) ?>',
                phone: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('phone')) ?>',
                postcode: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('postcode')) ?>',
                street: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('street_address')) ?>',
                extra_time: '<?php echo sprintf($this->lang->line('item_required'), $this->lang->line('extra_time')) ?>'
            },
            errorPlacement: function (error, element) {
                errorPlacement(error, element);
            }
        });
    }
    function warningForPreCheckDeliveryPlan(actualArea) {
        $.confirm({
            title: '<?php echo $this->lang->line('service_unavailable') ?>',
            message: '<?php echo $this->lang->line('delivery_service_not_provided_at') ?>' + actualArea + ' <?php echo $this->lang->line('area') . ' ' . $this->lang->line('still_continue') ?>',
            buttons: {
                '<span class="icon icon-check"></span>&nbsp;<?php echo $this->lang->line('yes') ?>': {
                    'class': 'positive',
                    'action': function () {
                        $('.page-loader').hide();
                        zamanDeliveryCustomPlanControllerPopup(actualArea);
                    }
                },
                '<span class="icon icon-cancel"></span>&nbsp;<?php echo $this->lang->line('no') ?>': {
                    'class': 'negative',
                    'action': function () {
                        $('.page-loader').hide();
                    }
                }
            }
        });
    }
    function preCheckDeliveryPlan(area, fee, minOrder, waitingTime) {
        var deliveryTimeObj = new Date();
        var extraTime = Number($('#deliveryExtraTime').val());
        var newExtraTime = extraTime > 0 ? extraTime : 0;
        deliveryTimeObj.setMinutes(deliveryTimeObj.getMinutes() + newExtraTime + waitingTime);
        var customerDeliveryInfo = {
            name: $('#deliveryCustomerName').val(),
            phone: $('#deliveryCustomerPhone').val(),
            building: $('#deliveryCustomerBuilding').val(),
            floor: $('#deliveryCustomerFloor').val(),
            apartment: $('#deliveryCustomerApartment').val(),
            sector: $('#deliveryCustomerRoadNumber').val(),
            street: $('#deliveryCustomerStreet').val(),
            postcode: formatPostcode($('#deliveryCustomerPostcode').val()),
            area: $.trim($('#deliveryCustomerArea').val()) ? $('#deliveryCustomerArea').val() : area,
            city: $('#deliveryCustomerCity').val(),
            region: $('#deliveryCustomerRegion').val(),
            country: $('#deliveryCustomerCountry').val(),
            deliveryTime: deliveryTimeObj.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'}),
            deliveryCharge: fee,
            minOrderAmount: minOrder
        };
        checkAndSubmitDeliveryInfo(customerDeliveryInfo);
    }
    function checkAndSubmitDeliveryInfo(customerData) {
        addLookupAddress(customerData);
        var existingDeliveryCustomerPhone = $('#existingDeliveryCustomerPhone').val();
        var existingDeliveryOrderId = Number($('#deliveryOrderId').val());
        if (existingDeliveryOrderId > 0) {
            var isConvertedToDelivery = $('#isConvertedToDelivery').val();
            var isConvertedToDeliveryPrice = $('#isConvertedToDeliveryPrice').val();
            if (isConvertedToDelivery === 'yes') {
                zamanEposDb.epos_customer.get({phone: customerData.phone}).then(function (aCustomer) {
                    if (typeof (aCustomer) !== 'undefined') {
                        customerData.lcid = aCustomer.lid;
                        zamanEposDb.epos_customer_address.get({lcid: aCustomer.lid}).then(function (thisCustomerAddress) {
                            if (typeof (thisCustomerAddress) !== 'undefined') {
                                customerData.lid = thisCustomerAddress.lid;
                            } else {
                                zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                    if (savedAddressId) {
                                        customerData.lid = savedAddressId;
                                    }
                                });
                            }
                        });
                    } else {
                        zamanEposDb.epos_customer.add({'name': customerData.name, phone: customerData.phone}).then(function (cid) {
                            if (cid) {
                                customerData.lcid = cid;
                                zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                    if (savedAddressId) {
                                        customerData.lid = savedAddressId;
                                    }
                                });
                            }
                        });
                    }
                }).then(function () {
                    eposConvertToDelivery(Number(existingDeliveryOrderId), isConvertedToDelivery, isConvertedToDeliveryPrice, customerData);
                }).then(function () {
                    zamanEposDb.epos_order.get({orderId: Number(existingDeliveryOrderId)}).then(function (anOrder) {
                        if (anOrder.type === 'delivery') {
                            eposPostUpdateOnConvertToDelivery(Number(existingDeliveryOrderId), customerData);
                        }
                    });
                });
            } else {
                zamanEposCart.setDeliveryCharge(customerData.deliveryCharge);
                updateDeliveryOrderInfo(existingDeliveryCustomerPhone, customerData);
            }
        } else {
            zamanEposDb.epos_customer.get({phone: customerData.phone}).then(function (aCustomer) {
                if (typeof (aCustomer) !== 'undefined') {
                    customerData.lcid = aCustomer.lid;
                    zamanEposDb.epos_customer_address.get({lcid: aCustomer.lid}).then(function (aCustomerAddress) {
                        if (typeof (aCustomerAddress) !== 'undefined') {
                            customerData.lid = aCustomerAddress.lid;
                            saveEposOrder(customerData, 'delivery');
                        } else {
                            zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                if (savedAddressId) {
                                    customerData.lid = savedAddressId;
                                    saveEposOrder(customerData, 'delivery');
                                }
                            });
                        }
                    });
                } else {
                    zamanEposDb.epos_customer.add({'name': customerData.name, phone: customerData.phone}).then(function (cid) {
                        if (cid) {
                            customerData.lcid = cid;
                            zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                if (savedAddressId) {
                                    customerData.lid = savedAddressId;
                                    saveEposOrder(customerData, 'delivery');
                                }
                            });
                        }
                    });
                }
            });
        }
    }

    function addLookupAddress(customerData) {
        zamanEposDb.epos_ldooraddress.get({'street_number': customerData.sector, 'route': customerData.street, 'administrative_area_level_2': customerData.city, 'postal_code': customerData.postcode}).then(function (checkedAddress) {
            if (typeof (checkedAddress) === 'undefined') {
                zamanEposDb.epos_ldooraddress.add({'street_number': customerData.sector, 'route': customerData.street, 'postal_town': '', 'administrative_area_level_2': customerData.city, 'postal_code': customerData.postcode}).then(function (lid) {
                    console.log(lid);
                });
            }
        });
    }
    function  updateDeliveryOrderInfo(existingBarCustomerPhone, customerData) {
        if (customerData.phone === existingBarCustomerPhone) {
            zamanEposDb.epos_customer.get({phone: existingBarCustomerPhone}).then(function (aCustomer) {
                if (typeof (aCustomer) !== 'undefined') {
                    customerData.lcid = aCustomer.lid;
                    zamanEposDb.epos_customer_address.get({lcid: aCustomer.lid}).then(function (thisCustomerAddress) {
                        if (typeof (thisCustomerAddress) !== 'undefined') {
                            customerData.lid = thisCustomerAddress.lid;
                            updateCustomerAddress(customerData);
                        } else {
                            zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                if (savedAddressId) {
                                    customerData.lid = savedAddressId;
                                    updateCustomerAddress(customerData);
                                }
                            });
                        }
                    });
                }
            });
        } else {
            zamanEposDb.epos_customer.get({phone: customerData.phone}).then(function (thisCustomer) {
                if (typeof (thisCustomer) !== 'undefined') {
                    customerData.lcid = thisCustomer.lid;
                    zamanEposDb.epos_customer_address.get({lcid: thisCustomer.lid}).then(function (thisCustomerAddress) {
                        if (typeof (thisCustomerAddress) !== 'undefined') {
                            customerData.lid = thisCustomerAddress.lid;
                            updateCustomerAddress(customerData);
                        } else {
                            zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                if (savedAddressId) {
                                    customerData.lid = savedAddressId;
                                    updateCustomerAddress(customerData);
                                }
                            });
                        }
                    });
                } else {
                    zamanEposDb.epos_customer.add({'name': customerData.name, phone: customerData.phone}).then(function (cid) {
                        if (cid) {
                            customerData.lcid = cid;
                            zamanEposDb.epos_customer_address.add(customerData).then(function (savedAddressId) {
                                if (savedAddressId) {
                                    customerData.lid = savedAddressId;
                                    updateCustomerAddress(customerData);
                                }
                            });
                        }
                    });
                }
            });
        }
    }
    function updateCustomerAddress(customerData) {
        zamanEposDb.epos_order.where("orderId").equals(Number(zamanEposCart.getEposCurrentId())).modify({
            orderInfo: customerData
        }).then(function (status) {
            zamanEposDb.epos_order.get({'orderId': Number(zamanEposCart.getEposCurrentId())}).then(function (theOrder) {
                if (theOrder.status >= 2 && status) {
                    var cart = zamanEposCart.listCart();
                    if (cart.length > 0) {
                        resentCart(Number(theOrder.orderId), cart, '<?php echo $this->lang->line('send_update') ?>', '<?php echo $this->lang->line('send_update_msg') ?>');
                    }
                }
            });
        }).then(function () {
            zamanEposDb.epos_order.get({'orderId': Number(zamanEposCart.getEposCurrentId())}).then(function (theOrder) {
                manageOrderListDisplay(theOrder, true);
            });
        });
    }
    function eposConvertToDelivery(orderId, isConvertedTo, isConvertedToPrice, orderInfo) {
        zamanEposDb.transaction('rw', [zamanEposDb.epos_branch, zamanEposDb.epos_order, zamanEposDb.epos_discountplan, zamanEposDb.epos_discountmulti, zamanEposDb.epos_discountitem, zamanEposDb.epos_table, zamanEposDb.epos_menucategory, zamanEposDb.epos_menu, zamanEposDb.epos_menuselection], function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                if (theOrder.type === 'table') {
                    zamanEposDb.epos_table.where("tableNumber").equals(theOrder.orderInfo.tableNumber).modify({
                        status: '2'
                    });
                }
            }).then(function () {
                zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
                    type: 'delivery'
                });
            }).then(function () {
                if (isConvertedTo === 'yes' && isConvertedToPrice === 'out') {
                    zamanEposCart.changeToOutPrice();
                }
                zamanEposCart.resetOnConvert();
                zamanEposCart.setOnConvert();
                zamanEposCart.setDeliveryCharge(orderInfo.deliveryCharge);
            }).then(function () {
                var cartCalculator = zamanEposCart.cartCalculator();
                zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
                    orderInfo: orderInfo,
                    cart: zamanEposCart.listCart(),
                    subTotal: cartCalculator.cartSubtotal,
                    tax: cartCalculator.cartTaxTotal,
                    serviceCharge: cartCalculator.serviceCharge,
                    deliveryCharge: cartCalculator.deliveryCharge,
                    ccFee: cartCalculator.cartccFee,
                    discount: cartCalculator.specialDiscount,
                    promo: cartCalculator.cartPromoDiscountAmount,
                    multiDiscount: cartCalculator.cartMultiDiscountAmount,
                    grandTotal: cartCalculator.Total
                });
            });
        }).then(function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                manageOrderListDisplay(theOrder, true);
            });
        });
    }
    function eposPostUpdateOnConvertToDelivery(orderId, orderInfo) {
        var cartCalculator = zamanEposCart.cartCalculator();
        zamanEposDb.epos_order.where("orderId").equals(orderId).modify({
            orderInfo: orderInfo,
            cart: zamanEposCart.listCart(),
            subTotal: cartCalculator.cartSubtotal,
            tax: cartCalculator.cartTaxTotal,
            serviceCharge: cartCalculator.serviceCharge,
            deliveryCharge: cartCalculator.deliveryCharge,
            ccFee: cartCalculator.cartccFee,
            discount: cartCalculator.specialDiscount,
            promo: cartCalculator.cartPromoDiscountAmount,
            multiDiscount: cartCalculator.cartMultiDiscountAmount,
            grandTotal: cartCalculator.Total
        }).then(function () {
            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                if (theOrder.status >= 2 && checkInternetConnection()) {
                    $.ajax('<?php echo site_url('api/epos_order') ?>', {
                        type: 'post',
                        dataType: 'json',
                        data: {
                            theOrder: theOrder,
                            type: '2',
                            sent: '2',
                            additionals: 'Ref ' + theOrder.sid + '/' + theOrder.orderId + ' is now delivery'
                        },
                        success: function (data) {
                            zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                                if (data.status) {
                                    manageOrderListDisplay(theOrder, true);
                                } else {
                                    manageOrderListDisplay(theOrder, true);
                                }
                            });
                        }
                    });
                } else {
                    zamanEposDb.epos_order.get({'orderId': orderId}).then(function (theOrder) {
                        manageOrderListDisplay(theOrder, true);
                    });
                }
            });
        });
    }
    function listDeliveryOrder(all) {
        $('#placeOrderTypeBlock').hide();
        $('.menu-category.menu-button-inner').removeClass('active');
        if (all !== 'yes') {
            $('.footer-order-list-button').removeClass('active');
            $('#list-delivery-only').addClass('active');
            $('#isToShowAllOrders').val('no');
            clearEposWorkAreaForOrderList('EposOrderListAreaDelivery');
            $('#categoryBreadcurm').hide();
            $('#eposCategoryMenuList').hide();
            playBeepSound();
        } else {
            $('#isToShowAllOrders').val('yes');
        }
        zamanEposDb.epos_order.where({'source': 'epos'}).filter(function (anDeliveryOrder) {
            var userData = zamanEposCart.getUserData();
            return anDeliveryOrder.type === 'delivery' && Number(anDeliveryOrder.branch) === Number(userData.branch) && Number(anDeliveryOrder.team) === Number(userData.team);
        }).toArray().then(function (deliveryOrders) {
            var html = ``;
            if (deliveryOrders.length > 0) {
                deliveryOrders.forEach(function (deliveryOrder) {
                    if (Number(deliveryOrder.status) <= 4) {
                        var isPaid = Number(deliveryOrder.isPaid) === 3 ? '(<?php echo $this->lang->line('paid') ?>)' : '&nbsp;';
                        html += `<div class="pane-content">
                        <div class="zaman-nav-item-pane">
                            <div class="order-item-img-block pull-left delivery-bg order-process-status-` + deliveryOrder.status + `" onclick="eposLoadOrder(` + deliveryOrder.orderId + `,'no')">
                                <p class="text-capitalize" style="line-height:0.9;">` + isPaid + `<br/> <img class="delivery-icon" alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQMAAABtzGvEAAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAAA1JREFUeNpjYBgF1AQAAVAAATS4OtkAAAAASUVORK5CYII=" style="width:36px; height:30px"><br/>` + deliveryOrder.orderInfo.name + `<br/>` + deliveryOrder.orderInfo.deliveryTime + `</p>
                            </div>
                        </div>
                    </div>`;
                    }
                });
                html += `<div class="clearfix">&nbsp;</div>`;
            }
            $('#EposOrderListAreaDelivery').html(html).show();
        });
    }
</script>
<?php $this->load->view('deliveryCustomPlan'); ?>






