var hallId = 0;
var tableId = 0;
var hallPrice = 0;


shortcut.add("f2", function () {
    $("#printKitchen").click();
    return false;
});
shortcut.add("f3", function () {
    if ($("#endPrintBill").length > 0) {
        $("#endPrintBill").click();
    } else {
        $("#printKitchen").click();
    }
    return false;
});


//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');
});
//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 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);
    }

    //
    $('#add-table').modal('hide');
    if (tableId == -2 || tableId == -1) {
        $('#deliveryPart').show();
    } else {

        if (clientShowTawla == 0) {
            $('#client').val(1);
            $('#deliveryPart').hide();
            $('.div_client_id').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();
            $('.div_client_id').hide();

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

        }
    }

    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);
});
//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 () {
    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 + '"]').parent().parent().parent().css('display', 'block');
    if (serachName == "") {
        $('.proName').parent().parent().parent().css('display', 'block');
    }
});
/*-- 4 buttons click ---------------------------------------------------------*/
//sendKitchen event

$('#zerobill').live('click', function () {
    var totalBill = $('#totalBill').val();
    if (totalBill > 0)
        updatepriceAndTotalOrder(tableId)

    $('#discount').attr('value', totalBill);
    $('#netBill').val(0);
    $('#totalBill_hidden').attr('value', '0');
    $('#payed').val(0);
    $('.payed').val(0);
    $('#payed').attr("disabled", true);
    $('#ba2ey').val(totalBill);
    $('#ba2ey_hidden').val(totalBill);
    $('#netBill_hidden').val(0);

    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
            $('#payed').val($('#netBill_hidden').val());
            $('.payed').val($('#netBill_hidden').val());
        }
        $('#saveOrderForm').submit();
    }


});

$('#sendKitchen').live('click', function () {
    printKitchen(tableId, 0);
});
//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 ba2ey = $('#ba2ey').val();
            if (ba2ey > 0) {
                $('#payed').val();
                $('.payed').val();
            } else {
                $('#payed').val($('#netBill_hidden').val());
                $('.payed').val($('#netBill_hidden').val());
            }

        }
        $('#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());
            $('.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 + '">' + 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
            }
        }
    });
}
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 moveTable(oldTable, newTableObj) {
    var clientShowTawla = $('#clientShowTawla').val();
    $.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("").change();
                    $('#deliveryPart').hide();
                    $('.div_client_id').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);
                    $('.client_id').val(client.clientname);

                } 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').val(discount);
//     }

//     $('#totalBill').val(total);
//     $('#totalBill_hidden').val(total);

//     //calc tax
//     if ($('#thereIsRestTax').val() == "1") {
//         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);
//         $('#payed').val(netBill);

//     } else {
//         var billTax = 0;
//         $('#payed').val(netBill);
//     }
//     //calc net

//     var ba2ey = $('#ba2ey').val();

//     if (discount > 0) {
//         alert('test')
//         if (ba2ey > 0) {
//             alert('test2')
//             var payed = Number($("#payed").val());
//             var netBill = total - discount + billTax;
//             netBill = Math.round(netBill * 100) / 100;//round
//             $('#netBill').val(Number(netBill));
//             $('#netBill_hidden').val(netBill);


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

//             if (payed > 0) {
//                 $('#ba2ey').val(netBill - Number($('#payed').val()));
//                 $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
//             } else {
//                 $('#ba2ey').val(netBill);
//                 $('#ba2ey_hidden').val(netBill);
//             }

//         }

//     } else if (ba2ey > 0) {

//         var payed = Number($("#payed").val());
//         var totalBill = Number($('#totalBill').val());

//         $('#netBill').val(Number(totalBill));
//         $('#netBill_hidden').val(totalBill);



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

//         if (payed > 0) {
//             $('#ba2ey').val(netBill - Number($('#payed').val()));
//             $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
//         } else {
//             $('#ba2ey').val(totalBill);
//             $('#ba2ey_hidden').val(totalBill);
//         }

//     } else {
//         var netBill = total - discount + billTax;
//         netBill = Math.round(netBill * 100) / 100;//round
//         $('#netBill').val(Number(netBill));
//         $('#netBill_hidden').val(netBill);

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


//         if (payed > 0) {
//             $('#ba2ey').val(netBill - Number($('#payed').val()));
//             $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
//         } else {
//             $('#ba2ey').val(total);
//             $('#ba2ey_hidden').val(total);
//         }
//     }







//     var totalQuantity = 0;
//     $('.quantity').each(function () {
//         totalQuantity += Number($(this).html());
//     });
//     $('#totalQuantity').val(totalQuantity);
// }


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').val(discount);
    }

    $('#totalBill').val(total);
    $('#totalBill_hidden').val(total);

    //calc tax
    if ($('#thereIsRestTax').val() == "1") {
        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);
        $('#payed').val(netBill);

    } else {
        var billTax = 0;
        if (Number($('#kitchenPayedVal').val()) == 1) {
            $('#payed').val(netBill);
        }

    }
    //calc net

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

    if (discount > 0) {
        alert('test')
        if (ba2ey > 0) {
            alert('test2')
            var payed = Number($("#payed").val());
            var netBill = total - discount + billTax;
            netBill = Math.round(netBill * 100) / 100;//round
            $('#netBill').val(Number(netBill));
            $('#netBill_hidden').val(netBill);


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

            if (payed > 0) {
                $('#ba2ey').val(netBill - Number($('#payed').val()));
                $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
            } else {
                $('#ba2ey').val(netBill);
                $('#ba2ey_hidden').val(netBill);
            }

        }

    } else if (ba2ey > 0) {
        var payed = Number($("#payed").val());
        var totalBill = Number($('#totalBill').val());

        $('#netBill').val(Number(totalBill));
        $('#netBill_hidden').val(totalBill);



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

        if (payed > 0) {
            $('#ba2ey').val(netBill - Number($('#payed').val()));
            $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
        } else {
            $('#ba2ey').val(totalBill);
            $('#ba2ey_hidden').val(totalBill);
        }

    } else {

        var netBill = total - discount + billTax;
        netBill = Math.round(netBill * 100) / 100;//round
        $('#netBill').val(Number(netBill));
        $('#netBill_hidden').val(netBill);

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

        if (Number($("#payed").val()) > 0) {
            $('#ba2ey').val(netBill - Number($('#payed').val()));
            $('#ba2ey_hidden').val(netBill - Number($('#payed').val()));
        } else {

            $('#ba2ey').val(total);
            $('#ba2ey_hidden').val(total);
        }
    }







    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').val(Number(netBill));
    $('#netBill_hidden').val(netBill);
    $('#payed').val(netBill);

//    الخصم

});

$("#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');
        });
    }
});

$('#payed').live('keyup', function () {
    var payed = Number($(this).val());
    var netBill_hidden = Number($('#netBill_hidden').val());

    var Residual = Number(netBill_hidden - payed);
    $('#ba2ey').val(Residual);
    $('#ba2ey_hidden').val(Residual);
    $('.payed').val(payed);
    $('#payed').val(payed);




})


//
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) {
        $(".table-active[data-table='" + tableidedit + "']").click();
    }


// $('.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 () {
    $("#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});
    }
    $("#client").live('change', function (e) {

        // alert(11);
        var val = $(this).val();
        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);
                    $(".client_id").val(data.clientname);
                    $('#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]});

                        $(".clien_id").val(data[1]);


                        $(':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();
});


function updatepriceAndTotalOrder(tableId) {
    $('.orderDetails').show();
    $.ajax({
        type: 'POST',
        url: 'sellbillAjaxController.php?do=updatepriceAndTotalOrder',
        data: {tableId: tableId},
        async: false,
        success: function (data) {

        }
    });
}
