var hallId = 0;
var tableId = 0;
var hallPrice = 0;
//table click open bill forms
$('.table-active').live('click', function () {
    hallId = $(this).attr('data-hall');
    hallPrice = $(this).attr('data-hall-price');
    tableId = $(this).attr('data-table');
    var table_name = $(this).attr('data-table-name');
    if (tableId == -2) {
        $('#hallNo').html("دليفرى");
        $('#tableNo').html("دليفرى");
    } else if (tableId == -1) {
        $('#hallNo').html("تيك أواى");
        $('#tableNo').html("تيك أواى");
    } else {
        $('#hallNo').html(hallId);
        $('#tableNo').html(table_name);
    }

    //
    $('.table-screen').css('display', 'none');
    $('.body_res').css('display', 'block');
    $('.exit-icon').toggle('display', 'block');
});


$('#printonly').live('click', function () {
     var tableid = $(this).attr('data-tableid');
     var billTax = $("#billTax").val();
    // window.location.href = 'http://example.com';
window.open("sellbillprintController.php?do=printResBillonly&id="+tableid+"&billTax="+billTax, '_blank');

});

// $('.changeOrderProduct').live('click', function () {
//     var id = $(this).attr('data-id');
//     $('#changeOrderProductid').val(id);
// });

$('#restauranttable').live('change', function () {
    // var orderid = $('#changeOrderProductid').val();
    var tabid =$(this).val();
    $('input.changeOrderProduct:checkbox:checked').each(function () {
         var orderid = $(this).attr('data-id');
        // if (orderid > 0) {
        $.ajax({
            type: 'POST',
            url: 'sellbillAjaxController.php?do=changeproorder',
            data: {orderid: orderid, tabid: tabid},
            async: false,
            success: function (data) {
               $('#orderid'+orderid).remove();
                // $('#changeOrderProductid').val(0);
                calcTotal(1, 1);
            }
        });

        // }else{
        //     alert('يجب اختيار منتج على الاقل');
        // }
    });
   

});
//choose another open table
$('.changeTable').live('click', function () {
    hallId = $(this).attr('data-hall');
    hallPrice = $(this).attr('data-hall-price');
    tableId = $(this).attr('data-table');
    var table_name = $(this).attr('data-table-name');
    var ClientShowTkaWay = $('#ClientShowTkaWay').val();
    var clientShowTawla = $('#clientShowTawla').val();
    if (tableId == -2) {
        $('#hallNo').html("دليفرى");
        $('#tableNo').html("دليفرى");
    } else if (tableId == -1) {
        $('#hallNo').html("تيك أواى");
        $('#tableNo').html("تيك أواى");
    } else {

        $('#hallNo').html(hallId);
        $('#tableNo').html(table_name);
    }
    // $("a#printonly").attr("href", "sellbillprintController.php?do=printResBillonly&id="+tableId);
$("a#printonly").attr("data-tableid", tableId);
    //
    $('#add-table').modal('hide');
    if (tableId == -2 || tableId == -1) {
        $('#deliveryPart').show();
    } else {
        if (clientShowTawla == 0) {
            $('#client').val(1);
            $('#deliveryPart').hide();

        } else {
            $('#deliveryPart').show();

        }
    }
    getBillComment();
    //to get table prices
    getFoodMenu(tableId);

    checktakeAwayClient(tableId);
});
//to open table event
$('.openTable').live('click', function () {
    hallId = $(this).attr('data-hall');
    hallPrice = $(this).attr('data-hall-price');
    tableId = $(this).attr('data-table');
    var clientShowTawla = $('#clientShowTawla').val();
    if (tableId == -1 || tableId == -2) {
        $('#deliveryPart').show();
    } else {
        if (clientShowTawla == 0) {
            $('#client').val(1);
            $('#deliveryPart').hide();

        } else {
            $('#deliveryPart').show();

        }
    }
    $("a#printonly").attr("data-tableid", tableId);
// $("a#printonly").attr("href", "sellbillprintController.php?do=printResBillonly&id="+tableId);
    checktakeAwayClient(tableId);

    openTable(tableId, hallId);
    //getBillComment();//it new no comment exist make sure its empty
    $('#billComment').val("");
    //to get table prices
    getFoodMenu(tableId);
});

$('.add-table').live('click', function () {
    $('#add-table').modal('show');
    $('.showClosedOnly').click();
});
//to move order from table to table event."like person move to another table"
$('.moveTableModalShow').live('click', function () {
    $('#move-table-modal').modal('show');
    $("#move-table-modal [data-table='" + tableId + "']").hide();//hide current table choose any other table to move to
    $('.showClosedOnly').click();
});
$('.moveTable').live('click', function () {
    var oldTable = tableId;
    var newTableObj = $(this);
    moveTable(oldTable, newTableObj);
});
$('.shoAllTables').live('click', function () {
    $('#add-table .table-block').show();
    $('#move-table-modal .table-block').show();
    $("#move-table-modal [data-table='" + tableId + "']").hide();//hide current table choose any other table to move to
});
$('.showClosedOnly').live('click', function () {
    $('#add-table .statusIsOpen').hide();
    $('#move-table-modal .statusIsOpen').hide();
});

//choose cat event
$('.parent-menu li a').live('click', function () {
    var catId = $(this).attr('data-cat');

    $('.parent-menu').css('display', 'none');
    $('.category-menu').css('display', 'block');
    //hide all products and show products of this cat
    $('.category-menu a[data-cat!="' + catId + '"]').css('display', 'none');
    $('.category-menu a[data-cat="' + catId + '"]').css('display', 'block');
    // $('img.prev-icon').css('display','block');
});
//chooseProduct event
$('.chooseProduct').live('click', function () {
    var productId = $(this).attr('data-productId');
    addProductToOrder(productId, tableId);
});
//removeOrderProduct event
$('.removeOrderProduct').live('click', function () {
    var productId = $(this).attr('data-productId');
    var passworduservalue = $('#passworduservalue').val();
    var sellBillIdold = $('#sellBillIdold').val();

    if (passworduservalue != "" && sellBillIdold > 0) {
        $('#passwordmodel').modal('show');
        $('#passwordpro').val(productId);
        setTimeout(function () {
            $('#passworduser').focus();
        }, 500)
    } else {
        removeProductFromOrder(productId, tableId);
    }
});
function checkPasswordBeforeDeleteProduct() {
    var password = $('#passworduser').val();
    var productId = $('#passwordpro').val();
    var kindadd = $('#kindadd').val();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=checkremovepasswored',
        data: {password: password},
        async: false,
        success: function (data) {
            if (data == 1) {
                $('#passwordmodel').modal('hide');
                if (kindadd == 1) {
                    decreaseProductInOrder(productId, tableId);
                } else {
                    removeProductFromOrder(productId, tableId);
                }

            } else {
                alert('باسور خظأ ');
            }
            $('#passworduser').val('');



        }
    });
}
$('#passworduser').live('change', function () {
    checkPasswordBeforeDeleteProduct();
});
$('#passworduser').live('keydown', function (e) {
    if (e.keyCode == 13) {
        checkPasswordBeforeDeleteProduct();
    }
});


//drinkDetails event
$('.drinkDetails').live('click', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var productId = $(this).attr('data-productId');
    var itr = $(this).attr('data-itr');
    saveDrinkDetails(productId, tableId, itr);

});
//decreaseProQuantity event
$('.decreaseProQuantity').live('click', function () {
    var productId = $(this).attr('data-productId');
    var passworduservalue = $('#passworduservalue').val();
    var sellBillIdold = $('#sellBillIdold').val();
    $('#kindadd').val(1);

    if (passworduservalue != "" && sellBillIdold > 0) {
        $('#passwordmodel').modal('show');
        $('#passwordpro').val(productId);
        setTimeout(function () {
            $('#passworduser').focus();
        }, 500)
    } else {
        decreaseProductInOrder(productId, tableId);
    }

});
//increaseProQuantity event
$('.increaseProQuantity').live('click', function () {
    var productId = $(this).attr('data-productId');
    increaseProductInOrder(productId, tableId);
});

$('.increaseProQuantitynew').live('change', function () {
    var productId = $(this).attr('data-productId');
    var quantitynew = $(this).val();
    increaseProductInOrdernew(productId, tableId, quantitynew);
});
//discount event
$('#discount').live('keyup', function () {
    calcTotal(1, 1);
});
// prev icon click
$('.prev-icon').live('click', function () {//img.prev-icon
    $('.parent-menu').css('display', 'block');
    $('.category-menu').css('display', 'none');
    // $('img.prev-icon').css('display','none');
});
//search products event
$('#query').live('keyup', function (e) {
    var serachName = $(this).val();
    $('.parent-menu').css('display', 'none');
    $('.category-menu').css('display', 'block');
    //hide all products and show products of this cat
    $('.proName').parent().parent().parent().css('display', 'none');
    $('.proName[data-name*="' + serachName + '"], .proName[data-parcode*="' + serachName + '"]').parent().parent().parent().css('display', 'block');
    if (serachName == "") {
        $('.proName').parent().parent().parent().css('display', 'block');
    }
});
$('#query').live('keydown', function (e) {
    if (e.keyCode == 13) {
        e.preventDefault();
        e.stopPropagation();
        if ($('.chooseProduct:visible').length > 0) {
            $('.chooseProduct:visible').first().click();
            $('#query').val("");
//            setTimeout(function () {
//                $('.prev-icon').click();
//            })
        }
        return false;
    }
});
/*-- 4 buttons click ---------------------------------------------------------*/
//sendKitchen event
$('#sendKitchen').live('click', function () {
    printKitchen(tableId, 0);
    getOrderDetails(tableId)
});
//printKitchen event
$('#printKitchen').live('click', function () {
    printKitchen(tableId, 1);
});
$('#endPrintBill').live('click', function () {
    if (tableId == -2 && Number($('#client').val()) < 1 && $('.total_product').length > 0) {
        //there is products and  its is delivery so when saving the bill client is required
        alert('عفوا اختر عميل');
    } else {
        $('#printBill').val(1);
        calcTotal(0, $('#kitchenPayedChange').val());
        $('#tableId').val(tableId);

        if (Number($('#client').val()) == 1) {//nakdi
            var netBill_hidden = $('#netBill_hidden').val();
            $('#payed').val(netBill_hidden);
        }
        $('#saveOrderForm').submit();
    }

});
$('#endBill').live('click', function () {
    if (tableId == -2 && Number($('#client').val()) < 1 && $('.total_product').length > 0) {
        //there is products and  its is delivery so when saving the bill client is required
        alert('عفوا اختر عميل');
    } else {
        $('#printBill').val(0);
        calcTotal(0, $('#kitchenPayedChange').val());
        $('#tableId').val(tableId);

        if (Number($('#client').val()) == 1) {//nakdi
            $('#payed').val($('#netBill_hidden').val());
        }
        $('#saveOrderForm').submit();
    }
});
/*----------------------------------------------------------------------------*/

function openTable(tableId, hallId) {
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=openTable',
        data: {tableId: tableId},
        async: false,
        success: function (data) {
            data = JSON.parse(data);
            if (tableId == -2) {
                $('#hallNo').html("دليفرى");
                $('#tableNo').html("دليفرى");
            } else if (tableId == -1) {
                $('#hallNo').html("تيك أواى");
                $('#tableNo').html("تيك أواى");
            } else {
                $('#hallNo').html(hallId);
                $('#tableNo').html(data[2]);
            }
            var group = data[1];
            //loop for used tables
            var html = '';
            data[0].forEach(function (resTable) {
                if (resTable.beingUsed == 1 && resTable.del == 0 && (resTable.hallUsers.indexOf(group.usergroupid) > -1 || group.seeAllHalls == 1)) {
                    html += '<div class="glyph button-block changeTable statusIsOpen" data-table="' + resTable.id + '" data-table-name="' + resTable.name + '" data-hall="' + resTable.hallid + '" data-hall-price="' + resTable.hallid + '">' +
                            '<a href="javascript:;">' +
                            '    <div class="glyph-icon flaticon-padnote"></div>' +
                            '    <h4>' + resTable.name + '</h4>' +
                            '</a>' +
                            '</div>';
                }
            });
            $('#usedTables').html(html);
            //hide modal
            $('#add-table').modal('hide');
            //loop for all used tables
            var html = '';
            data[0].forEach(function (resTable) {
                if (resTable.del == 0 && (resTable.hallUsers.indexOf(group.usergroupid) > -1 || group.seeAllHalls == 1)) {

                    var tableClass = 'openTable statusIsClosed';
                    var img = '    <img src="../views/default/assets/img/resturant/table-deactive.png">';
                    var prefix = 'فتح';
                    if (resTable.beingUsed == 1) {
                        tableClass = 'changeTable statusIsOpen';
                        img = '    <img src="../views/default/assets/img/resturant/table-active.png">';
                        prefix = '';
                    }
                    //
                    html += '<li class="table-block ' + tableClass + '" data-table="' + resTable.id + '" data-hall="' + resTable.hallid + '" data-hall-price="' + resTable.hallid + '">' +
                            '<a href="javascript:;">' + img + ' ' +
                            '    <h5>' + prefix + ' ' + resTable.name + '</h5>' +
                            '</a>' +
                            '</li>';
                }
            });
            $('#notUsedTables').html(html);
            //now tables to use for move
            //now str replace But For All Occurance.as html.replace("openTable", "moveTable"); replace first occurance only
            html = html.split("openTable").join("moveTable");
            html = html.split("changeTable").join("moveTable");
            html = html.split("فتح").join("نقل");
            $('#notUsedTablesMove').html(html);
        }
    });
}
function getFoodMenu(tableId) {
    $('#catDiv').html("loading...");
    $('#foodDiv').html("loading...");
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=getFoodMenu',
        data: {tableId: tableId},
        async: false,
        success: function (data) {
            data = JSON.parse(data);
            var hallData = data[2];
            //draw cats of food
            var html = '';
            data[0].forEach(function (cat) {
                html += '<li>' +
                        '<a data-cat="' + cat.productCatId + '">';
                if (cat.logo != "" && cat.logo != ".") {

                    html += '<img src="../views/default/images/cat_image/' + cat.logo + '">';
                } else {
                    html += '<img src="../views/default/assets/img/resturant/food1.jpg">';
                }
                html += '<span>' + cat.productCatName + '</span>' +
                        '</a>' +
                        '</li>';
            });
            $('#catDiv').html(html);
            //draw products of food
            var html = '';
            data[1].forEach(function (product) {
                html += '<a href="javascript:;" class="chooseProduct" data-cat="' + product.productCatId + '" data-productId="' + product.productId + '">' +
                        '<div class="block">';
                if (product.logo != "" && product.logo != ".") {
                    html += '<img src="../views/default/images/product_image/' + product.logo + '">';
                } else {
                    html += '<img src="../views/default/assets/img/resturant/food1.jpg">';
                }
                html += '<div class="info">' +
                        '    <span class="name proName" data-name="' + product.productName + '" data-parcode="' + product.parcode + '">' + product.productName + '</span>';
                var hallPrice = 0;
                if (hallData != null) {
                    hallPrice = Number(hallData.hallPrice)
                }
                switch (hallPrice) {
                    case 0:
                        html += '    <span class="price" data-productId="' + product.productId + '">' + product.productSellAllPrice + '</span>';
                        break;
                    case 1:
                        html += '    <span class="price" data-productId="' + product.productId + '">' + product.productSellUnitPrice + '</span>';
                        break;
                    case 2:
                        html += '    <span class="price" data-productId="' + product.productId + '">' + product.productSellHalfPrice + '</span>';
                        break;
                }

                html += ' </div>' +
                        '</div>' +
                        '</a>';
            });
            $('#foodDiv').html(html);

            $('.parent-menu').css('display', 'block');
            $('.category-menu').css('display', 'none');
            getOrderDetails(tableId);
        }
    });
}
function addProductToOrder(productId, tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=addProductToOrder',
        data: {productId: productId, tableId: tableId},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);

            calcTotal(1, 1);
            if (tableId == -1) {
                initiateDeliveryData();//to assign client 1 for the order
            }

            if ($('#quantity_' + productId)[0] && $('#quantity_' + productId)[0].is(':visible'))
                $('#quantity_' + productId)[0].focus();
        }
    });
}
function decreaseProductInOrder(productId, tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=decreaseProductInOrder',
        data: {productId: productId, tableId: tableId},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);
            calcTotal(1, 1);
        }
    });
}
function increaseProductInOrder(productId, tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=increaseProductInOrder',
        data: {productId: productId, tableId: tableId},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);
            calcTotal(1, 1);
        }
    });
}

function increaseProductInOrdernew(productId, tableId, quantitynew) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=increaseProductInOrder',
        data: {productId: productId, tableId: tableId, quantitynew: quantitynew},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);
            $('#quantity_' + productId)[0].focus();
            calcTotal(1, 1);
        }
    });
}
function moveTable(oldTable, newTableObj) {
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=moveTable',
        data: {oldTable: oldTable, tableId: newTableObj.attr("data-table")},
        async: false,
        success: function (data) {
            hallId = newTableObj.attr('data-hall');
            hallPrice = newTableObj.attr('data-hall-price');
            tableId = newTableObj.attr('data-table');

            //
            $('#move-table-modal').modal('hide');
            if (tableId == -2 || tableId == -1) {
                $('#deliveryPart').show();
            } else {
                if (clientShowTawla == 0) {
                    $('#client').val(1);
                    $('#deliveryPart').hide();

                } else {
                    $('#deliveryPart').show();

                }
            }

            data = JSON.parse(data);
            if (tableId == -2) {
                $('#hallNo').html("دليفرى");
                $('#tableNo').html("دليفرى");
            } else if (tableId == -1) {
                $('#hallNo').html("تيك أواى");
                $('#tableNo').html("تيك أواى");
            } else {
                $('#hallNo').html(hallId);
                $('#tableNo').html(data[2]);
            }
            var group = data[1];
            //loop for used tables
            var html = '';
            data[0].forEach(function (resTable) {
                if (resTable.beingUsed == 1 && resTable.del == 0 && (resTable.hallUsers.indexOf(group.usergroupid) > -1 || group.seeAllHalls == 1)) {
                    html += '<div class="glyph button-block changeTable statusIsOpen" data-table="' + resTable.id + '" data-table-name="' + resTable.name + '" data-hall="' + resTable.hallid + '" data-hall-price="' + resTable.hallid + '">' +
                            '<a href="javascript:;">' +
                            '    <div class="glyph-icon flaticon-padnote"></div>' +
                            '    <h4>' + resTable.name + '</h4>' +
                            '</a>' +
                            '</div>';
                }
            });
            $('#usedTables').html(html);
            //hide modal
            $('#add-table').modal('hide');
            //loop for all used tables
            var html = '';
            data[0].forEach(function (resTable) {
                if (resTable.del == 0 && (resTable.hallUsers.indexOf(group.usergroupid) > -1 || group.seeAllHalls == 1)) {

                    var tableClass = 'openTable statusIsClosed';
                    var img = '    <img src="../views/default/assets/img/resturant/table-deactive.png">';
                    var prefix = 'فتح';
                    if (resTable.beingUsed == 1) {
                        tableClass = 'changeTable statusIsOpen';
                        img = '    <img src="../views/default/assets/img/resturant/table-active.png">';
                        prefix = '';
                    }
                    //
                    html += '<li class="table-block ' + tableClass + '" data-table="' + resTable.id + '" data-hall="' + resTable.hallid + '" data-hall-price="' + resTable.hallid + '">' +
                            '<a href="javascript:;">' + img + ' ' +
                            '    <h5>' + prefix + ' ' + resTable.name + '</h5>' +
                            '</a>' +
                            '</li>';
                }
            });
            $('#notUsedTables').html(html);
            //now tables to use for move
            //str replace But For All Occurance.as html.replace("openTable", "moveTable"); replace first occurance only
            html = html.split("openTable").join("moveTable");
            html = html.split("changeTable").join("moveTable");
            html = html.split("فتح").join("نقل");
            $('#notUsedTablesMove').html(html);
            $(".changeTable[data-table='" + tableId + "']").click();
        }
    });
}
function checktakeAwayClient(table) {
    var takeAwayClient = $('#takeAwayClient').val();
    if (table == -1 && takeAwayClient == 0) {//take away & hide client
        $('#client').val(1);
        $('#deliveryPart').hide();
    }

}

function removeProductFromOrder(productId, tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=removeProductFromOrder',
        data: {productId: productId, tableId: tableId},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);
            calcTotal(1, 1);
        }
    });
}
function getOrderDetails(tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=getOrderDetails',
        data: {tableId: tableId},
        async: false,
        success: function (data) {
            $('#orderTBody').html(data);
            calcTotal(1, 1);
            initiateDeliveryData();
        }
    });
}
function initiateDeliveryData() {
    if (tableId == -2 || tableId == -1) {
        //delivert and no client yet see if there is one
        $.ajax({
            type: 'POST',
            url: 'sellbillAjaxController.php?do=getdeliveryClientData',
            data: {tableId: tableId},
            async: false,
            success: function (data) {
                if (data != "-1" && data != "-2") {
                    data = JSON.parse(data);
                    var delivery = data[0];
                    var client = data[1];
                    $("#client").select2("data", {id: client.clientid, text: client.clientname});

                    $('#activeUserDebt').html("");
                    $('#activeUserAddress').html("");
                    $('#activeUserMobile').html("");
                    var txtMobile = "";
                    if (delivery.clientmobile == 1) {
                        txtMobile += client.clientmobile;
                    }
                    if (delivery.clientphone == 1) {
                        if (delivery.clientmobile == 1) {
                            txtMobile += " - ";
                        }
                        txtMobile += client.clientphone;
                    }
                    $('#activeUserMobile').html(txtMobile);
                    if (delivery.clientaddress == 1) {
                        $('#activeUserAddress').html(client.clientaddress);
                    }
                    if (delivery.clientdetails == 1) {
                        $('#activeUserAddress').html(client.clientdetails);
                    }
                    $('#activeUserDebt').html(client.clientdebt);
                } else {
                    $("#client").select2("data", {id: "", text: ""});

                    $('#activeUserDebt').html("");
                    $('#activeUserMobile').html("");
                    $('#activeUserAddress').html();
                }
            }
        });
    }

}
function getBillComment() {
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=getBillComment',
        data: {tableId: tableId},
        async: false,
        success: function (data) {
            $('#billComment').val(data);
        }
    });

}
function calcTotal(changeTax, kitchenPayedChange) {//kitchenPayedChange is sent only in end bill events to decide,otherwise payed is calculated
    //calc total
    var total = 0;
    $('.total_product').each(function () {
        total += Number($(this).html());
    });
    var valueadded = Number($('#valueadded').val());
    if (valueadded == 1) {
        total = (total / 1.15).toFixed(3);
    }


    //check if disount in limits
    var discount = Number($('#discount').val());
    var groupPerDiscount = Number($('#groupPerDiscount').val());
    var maxAllowedDisount = total * (groupPerDiscount / 100);
    if (discount > maxAllowedDisount) {
        discount = maxAllowedDisount;
        $('#discount').val(discount);
    }
    $('#discount_hidden').val(discount)

    $('#totalBill').html(total);
    $('#totalBill_hidden').val(total);
    //console.log($('#billTax').is(':visible'))
    //calc tax
    if ($('#thereIsRestTax').val() == "1" && $('#billTax').is(':visible')) {
        var billTax = Number($('#billTax').val());
        var maxAllowedTax = (total - discount) * (Number($('#restTaxVal').val()) / 100);
        maxAllowedTax = Math.round(maxAllowedTax * 100) / 100;//round
        if (changeTax == 1) {
            billTax = maxAllowedTax;
        }

        // if (changeTax == 1 || billTax > maxAllowedTax) {
        //     billTax = maxAllowedTax;
        // }
        $('#restTaxVal_hidden').val(billTax);
        $('#billTax').val(billTax);

    } else {
        var billTax = 0;
        $('#restTaxVal_hidden').val(billTax);
        $('#billTax').val(billTax);
    }
    //calc net
    var netBill = total - discount + billTax;
    netBill = Math.round(netBill * 100) / 100;//round
    $('#netBill').html(netBill);
    $('#netBill_hidden').val(netBill);
    //$('#payed').val(netBill);

    //##total of totals
    var totalOfTotals = netBill + Number($('#psPrice').val());
    $('#totalOfTotals').text(totalOfTotals);

    if (Number($('#client').val()) == 1) {//nakdi
        $('#payed').val(netBill);
    } else {
        if (kitchenPayedChange == 1) {
            if (Number($('#kitchenPayedVal').val()) == 0) {
                $('#payed').val(netBill);
            } else {
                $('#payed').val(netBill);
            }
        }
    }


    var totalQuantity = 0;
    $('.quantity').each(function () {
        totalQuantity += Number($(this).html());
    });
    $('#totalQuantity').val(totalQuantity);
}
//search products event
$('#billTax').live('keyup', function () {
    var billTax = Number($(this).val());
    var total = Number($('#totalBill_hidden').val());
    var discount = Number($('#discount').val());
    var MaxAllowedTax = (total - discount) * (Number($('#restTaxVal').val()) / 100);
    MaxAllowedTax = Math.round(MaxAllowedTax * 100) / 100;//round
    // if (billTax > MaxAllowedTax) {
    //     billTax = MaxAllowedTax;
    // }
    $('#restTaxVal_hidden').val(billTax);
    $('#billTax').val(billTax);

    //calc net
    var netBill = total - discount + billTax;
    netBill = Math.round(netBill * 100) / 100;//round
    $('#netBill').html(netBill);
    $('#payed').val(netBill);
    $('#netBill_hidden').val(netBill);
});

//
function printKitchen(tableId, printNow) {
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=printKitchen',
        data: {tableId: tableId},
        async: false,
        success: function (data) {
            if (data != -1) {
                if (printNow == 1)
                {
                    $('#printOrderDiv').html(data);
                    setTimeout(function () {
                        printContent('printOrderDiv');
                        $('#printOrderDiv').html("");
                    }, 1000);
                }
            }

            // getOrderDetails(tableId);
        }
    });
}

function printContent(el) {
    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(el).innerHTML;
    document.body.innerHTML = printcontent;
    print_Custom('mycustomheader');
    document.body.innerHTML = restorepage;
    $('#billTax').val($('#restTaxVal_hidden').val());
    $('#discount').val($('#discount_hidden').val());
    $('#payed').val(Number($('#netBill').text()));

}


$(document).ready(function () {
    // 	if(window.innerHeight > window.innerWidth){
// 		alert("window.innerHeight > window.innerWidth");
//     alert("Please use Landscape!");
// }
    if (window.innerHeight > window.innerWidth) {
        alert("This page is best viewed in landscape mode,please rotate your Screen");
    }
    var tableidedit = $('#tableidedit').val();

    if (tableidedit) {

        var clientidedit = $('#clientidedit').val();
        var clienttextedit = $('#clienttextedit').val();
        $(".table-active[data-table='" + tableidedit + "']").click();
        $("#client").select2("data", {id: clientidedit, text: clienttextedit});
    }


// $('.add-table').click(function(){
// 	$("#add-table").css('display','block');
// })

});

function saveDrinkDetails(productId, tableId, itr) {
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=saveDrinkDetails',
        data: {productId: productId, tableId: tableId, itr: itr},
        async: false,
        success: function (data) {
            if (data != "")
            {
                $('#drinkDetailsInfo').html(data);
                $('#drinkDetailsModal').modal('show');
            }
        }
    });
}

$('.saveDrinkDetails').live('click', function (e) {
    e.preventDefault();
    if ($('#drinkDetailsInfo').valid()) {
        var notes = $('#notes').val();
        var quantity = Number($('#quantity').val());
        var printedQuantity = Number($('#printedQuantity').val());
        var thisItr = Number($('#thisItr').val());
        var total = 0;
        var totalStr = '';
        var totalAsNote = '';
        $('.drinkDetailsClass').each(function () {
            var val = Number($(this).val());

            var thisId = $(this).attr('id');
            total += val;
            switch (thisId) {
                case'sugarPlusPlus':
                    if (val != 0) {
                        totalStr += val + ' زيادة عالى ';
                    }
                    totalAsNote += val + ',';
                    break;
                case'sugarPlus':
                    if (val != 0) {
                        totalStr += val + ' زيادة ';
                    }
                    totalAsNote += val + ',';
                    break;
                case'mano':
                    if (val != 0) {
                        totalStr += val + ' مانو ';
                    }
                    totalAsNote += val + ',';
                    break;
                case'sugarExact':
                    if (val != 0) {
                        totalStr += val + ' مظبوط ';
                    }
                    totalAsNote += val + ',';
                    break;
                case'sugarMinus':
                    if (val != 0) {
                        totalStr += val + ' عالريحه ';
                    }
                    totalAsNote += val + ',';
                    break;
                case'sugarNo':
                    if (val != 0) {
                        totalStr += val + ' ساده ';
                    }
                    totalAsNote += val + ',';
                    break;
            }
        });
        totalStr = totalStr.slice(0, -1);
        totalAsNote = totalAsNote.slice(0, -1);
        if (total != quantity)
        {
            alert('عفوا لم تدخل تفاصيل كل الطلبات');
        } else {
            $('#notes' + thisItr).html(totalStr);
            $('#hiddenNotes' + thisItr).val(totalAsNote);
            var productId = $('#thisPro').val();
            $.ajax({
                type: 'POST',
                url: 'sellbillAjaxController.php?do=saveDrinkDetailsInDB',
                data: {productId: productId, tableId: tableId, totalAsNote: totalAsNote},
                async: false,
                success: function (data) {
                    if (data == 1) {
                        $('#drinkDetailsModal').modal('hide');
                    }

                }
            });
        }

    }
});
$('#billComment').live('blur', function (e) {
    $.post('sellbillAjaxController.php?do=billComment', {tableId: tableId, billComment: $('#billComment').val()}, function () {
    });
});


/*-----------------------------------------------------------*/
//plugin bootstrap minus and plus
//https://bootsnipp.com/snippets/featured/buttons-minus-and-plus-in-input

$('.btn-number').live('click', function (e) {
    e.preventDefault();

    fieldName = $(this).attr('data-field');
    type = $(this).attr('data-type');
    var input = $("input[name='" + fieldName + "']");
    var currentVal = parseInt(input.val());
    if (!isNaN(currentVal)) {
        if (type == 'minus') {

            if (currentVal > input.attr('min')) {
                input.val(currentVal - 1).change();
            }
            if (parseInt(input.val()) == input.attr('min')) {
                $(this).attr('disabled', true);
            }

        } else if (type == 'plus') {

            if (currentVal < input.attr('max')) {
                input.val(currentVal + 1).change();
            }
            if (parseInt(input.val()) == input.attr('max')) {
                $(this).attr('disabled', true);
            }

        }
    } else {
        input.val(0);
    }
});
$('.input-number').live('focusin', function (e) {
    $(this).data('oldValue', $(this).val());
});
$('.input-number').live('change', function (e) {

    minValue = parseInt($(this).attr('min'));
    maxValue = parseInt($(this).attr('max'));
    valueCurrent = parseInt($(this).val());

    name = $(this).attr('name');
    if (valueCurrent >= minValue) {
        $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        alert('عفوا وصلت للحد الادنى');
        $(this).val($(this).data('oldValue'));
    }
    if (valueCurrent <= maxValue) {
        $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        alert('عفوا وصلت للحد الاقصى');
        $(this).val($(this).data('oldValue'));
    }


});
$('.input-number').live('keydown', function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 190]) !== -1 ||
            // Allow: Ctrl+A
                    (e.keyCode == 65 && e.ctrlKey === true) ||
                    // Allow: home, end, left, right
                            (e.keyCode >= 35 && e.keyCode <= 39)) {
                // let it happen, don't do anything
                return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
/*-----------------------------------------------------------*/
//delivery part
$(document).ready(function () {
 $("#restauranttable").select2({
        placeholder: "اختر  ",
        minimumInputLength: 0,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "billsajax.php?do=restauranttable",
            dataType: 'json',
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {
                // alert(term);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return  data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });
    $("#client").select2({
        placeholder: "اختر عميل ",
        minimumInputLength: 0,
        //  minimumInputLength: 3,
        multiple: false,
        quietMillis: 100,
        ajax: {
            url: "billsajax.php?do=getclients",
            dataType: 'json',
            data: function (term, page) {
                //  alert(term);
                return {
                    term: term, //search term
                    page_limit: 10, // page size
                };
            },
            results: function (data) {
                // alert(term);
                return {results: data};
            }
        },
        formatResult: function (data) {
            return  data.text;
        },
        initSelection: function (element, callback) {
            var item = element.val().split(':');
            var data = {id: item[0], text: item[1]};
            callback(data);
        }
    });

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

    if (tableidedit) {

        var clientidedit = $('#clientidedit').val();
        var clienttextedit = $('#clienttextedit').val();
        $(".table-active[data-table='" + tableidedit + "']").click();
        $("#client").select2("data", {id: clientidedit, text: clienttextedit});
    }
    $("#getlastbill").live('click', function (e) {
        var val = $('#client').val();
        if (val > 0) {
            $.post('sellbillAjaxController.php?do=getlastbill', {id: val, kind: 2}, function (data) {
                $('.lastbillmodel').html(data);
                $('#lastbillmodel').modal('show');
            });
        }
    });

    $("#client").live('change', function (e) {

        // alert(11);
        var val = $(this).val();
        $.post('sellbillAjaxController.php?do=getlastbill', {id: val, kind: 1}, function (data) {
            $('#lastbill').html(data);
        });
        if (val == '-2') {
            $('#newclientName').val("");
            $('#clientcode').val("");
            $('#clientareaid').val("").change();
            $('#newclientdebt').val(0);
            $('#clientaddress').val("");
            $('#clientphone').val("");
            $('#clientmobile').val("");
            $('#clientdetails').val("");
            $('#myclientModal1').modal('show');
        } else if (val != "") {
            $('#activeUserDebt').html("");
            $('#activeUserMobile').html("");
            $('#activeUserAddress').html("");
            if (tableId != -1) {//as -1 "take away" has no required address or phone unlike delivery & table
                //choose client data"phone,address" to print
                $.post('clientControllerAjax.php?do=getclientdata', {id: val}, function (data) {
                    data = JSON.parse(data);
                    var phones = '';
                    if (data.clientmobile != "") {
                        phones += '<tr><td>' + data.clientmobile + '</td><td><input type="checkbox" class="clientData" id="clientmobileCheckBox" name="clientmobileCheckBox" value="1" data-txt="' + data.clientmobile + '" checked="checked"/></td></tr>';
                    }
                    if (data.clientphone != "") {
                        phones += '<tr><td>' + data.clientphone + '</td><td><input type="checkbox" class="clientData" id="clientphoneCheckBox" name="clientphoneCheckBox" value="1" data-txt="' + data.clientphone + '"  checked="checked"/></td></tr>';
                    }
                    if (phones == '') {
                        phones += '<tr><td colspan="2">لا يوجد ارقام لهذا العميل</td></tr>';
                    }
                    //
                    var address = '';
                    if (data.clientaddress != "") {
                        address += '<tr><td>' + data.clientaddress + '</td><td><input type="checkbox" checked class="clientData" id="clientaddressCheckBox" name="clientaddressCheckBox" value="1" data-txt="' + data.clientaddress + '"/></td></tr>';
                    }
                    if (data.clientdetails != "") {
                        address += '<tr><td>' + data.clientdetails + '</td><td><input type="checkbox" class="clientData" id="clientdetailsCheckBox" name="clientdetailsCheckBox" value="1" data-txt="' + data.clientdetails + '"/></td></tr>';
                    }
                    if (phones == '') {
                        address += '<tr><td colspan="2">لا يوجد عناوين لهذا العميل</td></tr>';
                    }
                    $('#clientdebtCell').html(data.clientdebt);
                    $('#clientphoneTBody').html(phones);
                    $('#clientAddressTBody').html(address);
                    $('#myclientDataModal1').modal('show');
                });
            }
        }
    });
    $('.savemodel1').on('click', function (e) {
        //alert($('#clientInfomain').validate().form())
        if ($('#clientInfomain').validate().form())
        {

            var newclientName = $('#newclientName').val();
            var clientcode = $('#clientcode').val();
            var clientareaid = $('#clientareaid').val();
            var newclientdebt = $('#newclientdebt').val();
            var clientaddress = $('#clientaddress').val();
            var clientphone = $('#clientphone').val();
            var clientmobile = $('#clientmobile').val();
            var clientdetails = $('#clientdetails').val();
            var taxnumber = $('#taxnumber').val();

            var emp = '';

            if (newclientName == '') {
                e.preventDefault();
                if ($('#nameError').html() == "")
                {
                    $('#nameError').append("<p style='color: red;'>ادخل اسم العميل </p>");
                }
            } else {
                $.post('clientControllerAjax.php?do=addclient3', {newclientName: newclientName, clientaddress: clientaddress, clientphone: clientphone, clientmobile: clientmobile, newclientdebt: newclientdebt, clientdetails: clientdetails, taxnumber: taxnumber, clientareaid: clientareaid, clientcode: clientcode, control: 1}, function (data) {

                    /// document.getElementById('').style.display = 'none';
                    $('#myclientModal1').modal('hide');
                    if (data == 2) {
                        alert('هذا العميل تمت اضافتة من قبل ');
                        //location.reload();
                    } else if (data == 3) {
                        alert('رقم الكود تمت اضافتة من قبل ');
                        //location.reload();
                    } else {
                        data = data.split(',');
                        $("#client").val(data[0]).change();
                        $("#client").select2("data", {id: data[0], text: data[1]});

                        //$("#clientDiv").html(data);


                        $(':input', '#clientInfo').val('');
                        $('#clientareaid').select2();
                    }
                });
            }

        }


    });
    $('.savemodel1Data').on('click', function (e) {
        if ($('.clientData:checked').length > 0) {
            if ($('#clientaddressCheckBox').is(":checked") && $('#clientdetailsCheckBox').is(":checked")) {
                alert('عفوا اختر عنوان واحد فقط');
            } else {
                $('#activeUserDebt').html("");
                $('#activeUserAddress').html("");
                $('#activeUserMobile').html("");
                var txtMobile = "";
                if ($('#clientmobileCheckBox').is(":checked")) {
                    txtMobile += $('#clientmobileCheckBox').attr('data-txt');
                }
                if ($('#clientphoneCheckBox').is(":checked")) {
                    if ($('#clientmobileCheckBox').is(":checked")) {
                        txtMobile += " - ";
                    }
                    txtMobile += $('#clientphoneCheckBox').attr('data-txt');
                }
                $('#activeUserMobile').html(txtMobile);
                if ($('#clientaddressCheckBox').is(":checked")) {
                    $('#activeUserAddress').html($('#clientaddressCheckBox').attr('data-txt'));
                }
                if ($('#clientdetailsCheckBox').is(":checked")) {
                    $('#activeUserAddress').html($('#clientdetailsCheckBox').attr('data-txt'));
                }
                $('#activeUserDebt').html($('#clientdebtCell').html());
                $.ajax({
                    type: 'POST',
                    url: 'sellbillAjaxController.php?do=saveDeliveryData',
                    data: $("#clientInfoDatamain").serialize() + "&tableId=" + tableId + "&clientId=" + $('#client').val(),
                    async: false,
                    success: function (data) {
                        $('#myclientDataModal1').modal('hide');
                    }
                });
            }
        } else {
            alert('عفوا لم تختر اى بيانات للعميل');
        }
    });
});
$(document).ready(function () {
    if ($('#printOrder').length > 0 && Number($('#printOrder').val()) > 0) {
        window.open("sellbillprintController.php?do=printResBill&id=" + Number($('#printOrder').val()));
    }

    var restaurantDefaultPage = $('#restaurantDefaultPage').val();
    //$("[data-table='-1']").first().click();
    $("[data-table='" + restaurantDefaultPage + "']").first().click();
});
