
function InitFirst() {

    Loading();

    $('body').css('padding-bottom', $('footer').outerHeight() + 20);

    $('#modalService').css('height', 'calc(100% - ' + $('footer').outerHeight() + 'px)');

    ReloadAppointment(false);

    ReloadSaleItems(false);

    ReloadCustomer(true);

    setInterval("ReloadAppointment(true);", 15000);
    setInterval("ReloadSaleItems(true);", 60000);
}

function ReloadCustomer(firstLoad) {
    if (firstLoad) {
        Loading();
    }
    $.ajax({
        url: _url.ReloadCustomer,
        type: 'GET',
        dataType: 'JSON',
        success: function (respon) {

            if (firstLoad) {
                RemoveLoading();
                Step1();
            }

            _signInStorage.Customers = respon.customers;
            _signInStorage.AllowDuplicatePhone = respon.allowDuplicatePhone;

        },
        error: function (xhr, ajaxOptions, thrownError) {
            if (firstLoad) {
                RemoveLoading();
                Step1();
            }
        }
    });
}

function ReloadAppointment(isAsync) {
    $.ajax({
        url: _url.ReloadAppointment,
        type: 'GET',
        async: isAsync,
        dataType: 'JSON',
        success: function (respon) {
            _signInStorage.Appointments = respon.appointments;
            _signInStorage.Technicians = respon.technicians;
            isNoService = respon.noService == 'true';
            isNoTechnician = respon.noTechnician == 'true';

            if (isNoService) {
                $('#btnClearAll,#btnShowSaleItem,#btnBackService').hide();
            } else {
                $('#btnClearAll,#btnShowSaleItem,#btnBackService').show();
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        }
    });
}

function ReloadSaleItems(isAsync) {
    $.ajax({
        url: _url.ReloadService,
        type: 'GET',
        async: isAsync,
        dataType: 'JSON',
        success: function (respon) {

            _signInStorage.Categories = respon.categories;
            _signInStorage.RowCats = respon.totalRowCat;

            _signInStorage.ServiceItems = respon.items;
            _signInStorage.RowItems = respon.totalRowItem;

        },
        error: function (xhr, ajaxOptions, thrownError) {
        }
    });
}

function Loading() {
    $('.loading-modal').remove();
    document.body.innerHTML += '<div class="loading-modal"><div class="loading-box"><div class="loading-icon"></div></div></div>';
}

function RemoveLoading() {
    $('.loading-modal').fadeOut(500, function () {
        $(this).remove();
    });
}

function ClearModal() {
    $('.lobibox-backdrop,body > .lobibox').remove();
    $('.modal-backdrop').remove();
}

function Step1() {

    ClearModal();

    $('#step1').show();
    $('#modalPhoneNumber,#modalCustomer,#modalService').hide();

    _signInStorage.stepCurrent = 1;

    //Lobibox.alert('info', {
    //    //title: '<h1 class="text-center">Welcome to<br>' + _storeName + '</h1>',
    //    //msg: '<h3>Do you have an appointment today?</h3>',
    //    title: '<h1 class="text-center">Welcome to</h1>',
    //    msg: '<h3 style="font-site:25pt;">' + _storeName + '</h3>',
    //    buttons: {
    //        yes: {
    //            'class': 'btn btn-success',
    //            closeOnClick: true,
    //            text: 'Sign In'
    //        }
    //        //yes: {
    //        //    'class': 'btn btn-success',
    //        //    closeOnClick: true
    //        //},
    //        //no: {
    //        //    'class': 'btn btn-warning',
    //        //    closeOnClick: true
    //        //}
    //    },
    //    callback: function (lobibox, type) {
    //        //if (type === 'no') {
    //        //    _signInStorage.hasAppointment = false;
    //        //} else if (type === 'yes') {
    //        //    _signInStorage.hasAppointment = true;
    //        //}
    //        Step2();
    //    }
    //});
}

function Step2() {
    $('#step1').hide();
    ClearModal();
    _signInStorage.stepCurrent = 2;
    $("#txtPhone").val('');
    $("#txtPhone").focus();
    $('#modalPhoneNumber').modalPhone({
        fullRequired: true,
        complete: function (e) {

            $('#modalPhoneNumber').hide();

            _signInStorage.customerPhone = e.GetPhoneFormatServer();

            CheckPhone();

        },
        exit: function () {
            Step1();
        }
    });


    return false;
}

function StepCheckPoint() {
    $('#step1').hide();
    ClearModal();
    _signInStorage.stepCurrent = 2;
    $("#txtPhone").val('');
    $("#txtPhone").focus();
    $('#modalPhoneNumber').modalPhone({
        fullRequired: true,
        complete: function (e) {

            $('#modalPhoneNumber').hide();

            _signInStorage.customerPhone = e.GetPhoneFormatServer();

            CheckPhonePoint();

        },
        exit: function () {
            Step1();
        }
    });


    return false;
}

function StepCheckIn() {
    $('#step1').hide();
    ClearModal();

    Loading();

    $.ajax({
        url: _url.CheckIn,
        type: 'POST',
        async: false,
        dataType: 'JSON',
        success: function (respon) {
            RemoveLoading();

            ClearModal();
            $('#modalCustomer').show();

            cusHtml = "";
            cusHtml += '<div class="panel-heading">Waiting List</div>';

            if (respon.status) {
                var data = respon.data;

                var table = '<table class="table table-bordered table-hover">';
                table += ' <tr><th>Customer Name</th><th style="width:150px;">Time SignIn</th></tr> ';
                data.forEach(function (cus) {
                    table += ' <tr><td>' + cus.Customer + '</td><td>' + cus.TimeSignIn + '</td></tr> ';
                });
                if (data.length == 0) {
                    table += ' <tr><td colspan="2" class="text-center">No data</td></tr> ';
                }
                table += '</table>';
                cusHtml += '<div class="panel-body">' + table + '</div>';
            } else {
                cusHtml += '<div class="panel-body"><div class="alert alert-warning">' + status.msg + '</div></div>';
            }

            cusHtml += '<div class="panel-footer"><button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return Step1();">Close</button></div>';
            $('#modalCustomer .panel').html(cusHtml);

        },
        error: function (xhr, ajaxOptions, thrownError) {
            RemoveLoading();
            Step1(1);
        }
    });

    return false;
}



function CheckPhonePoint() {

    $('#modalPhoneNumber,#modalCustomer,#modalService').hide();

    Loading();

    var customers = FilterCustomer(_signInStorage.customerPhone);

    RemoveLoading();

    if (customers.length == 0) {
        Lobibox.alert('warning', {
            title: 'Warning',
            msg: '<h3>Customer not found!</h3>',
            buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
            callback: function (lobibox, type) {
                Step1();
            }
        });
    } else {
        if (customers.length == 1) {

            var customer = customers[0];

            Lobibox.alert('info', {
                title: 'Confirm',
                msg: '<h3>You are "' + customer.FullName + '"?</h3>',
                buttons: {
                    yes: {
                        'class': 'btn btn-success',
                        closeOnClick: true
                    },
                    no: {
                        'class': 'btn btn-warning',
                        closeOnClick: true
                    }
                },
                callback: function (lobibox, type) {
                    if (type === 'no') {
                        Step1();
                    } else if (type === 'yes') {

                        Loading();

                        $.ajax({
                            url: _url.CheckReWard,
                            type: 'POST',
                            async: false,
                            data: { id: cus.ID },
                            dataType: 'JSON',
                            success: function (respon) {
                                RemoveLoading();

                                ClearModal();
                                $('#modalCustomer').show();
                                cusHtml = "";

                                if (respon.status) {
                                    var data = respon.data;
                                    cusHtml += '<div class="panel-heading">Hello ' + data.FullName + '</div>';
                                    cusHtml += '<div class="panel-body">You have<br> - Reward Point: $' + data.TotalPoint + '<br>- Reward Discount: $' + data.DiscountPoint + '</div>';
                                } else {
                                    cusHtml = "";
                                    cusHtml += '<div class="panel-heading">Warning</div>';
                                    cusHtml += '<div class="panel-body">Not Found Customer!</div>';
                                }

                                cusHtml += '<div class="panel-footer"><button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return Step1();">Close</button></div>';
                                $('#modalCustomer .panel').html(cusHtml);

                            },
                            error: function (xhr, ajaxOptions, thrownError) {
                                RemoveLoading();
                            }
                        });

                    }
                }
            });
        } else {
            ClearModal();
            $('#modalCustomer').show();

            var cusHtml = "";
            cusHtml += '<div class="panel-heading">You are ...</div>' +
                            '<div class="panel-body">';
            customers.forEach(function (v, i) {
                cusHtml += '<button type="button" class="btn-customer btn btn-default btn-lg btn-block" data-index="' + i + '">' + v.FullName + '</button>';
            });
            cusHtml += '<button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return Step1();">No</button>' +
                        '</div>';
            $('#modalCustomer .panel').html(cusHtml);
            $('#modalCustomer .btn-customer').click(function () {
                var iIndex = $(this).data('index');

                var cus = customers[iIndex];

                Loading();

                $.ajax({
                    url: _url.CheckReWard,
                    type: 'POST',
                    async: false,
                    data: { id: cus.ID },
                    dataType: 'JSON',
                    success: function (respon) {
                        RemoveLoading();

                        ClearModal();
                        $('#modalCustomer').show();
                        cusHtml = "";

                        if (respon.status) {
                            var data = respon.data;
                            cusHtml += '<div class="panel-heading">Hello ' + data.FullName + '</div>';
                            cusHtml += '<div class="panel-body">You have<br> - Reward Point: $' + data.TotalPoint + '<br>- Reward Discount: $' + data.DiscountPoint + '</div>';
                        } else {
                            cusHtml += '<div class="panel-heading">Warning</div>';
                            cusHtml += '<div class="panel-body">Not Found Customer!</div>';

                        }
                        cusHtml += '<div class="panel-footer"><button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return Step1();">Close</button></div>';
                        $('#modalCustomer .panel').html(cusHtml);

                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        RemoveLoading();
                    }
                });


                //cusHtml = "";
                //cusHtml += '<div class="panel-heading">Hello ' + cus.FullName + '</div>';

                //cusHtml += '<div class="panel-body">You have<br> - Reward Point: $' + cus.TotalPoint + '<br>- Reward Discount: $' + cus.DiscountPoint + '</div>';
                //cusHtml += '<div class="panel-footer"><button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return Step1();">Close</button></div>';
                //$('#modalCustomer .panel').html(cusHtml);


            });
        }
    }

    return false;

}


function CheckPhone() {

    $('#modalPhoneNumber,#modalCustomer,#modalService').hide();

    Loading();

    var customers = FilterCustomer(_signInStorage.customerPhone);

    RemoveLoading();

    if (customers.length == 0) {
        AddNewCustomer();
        //if (_signInStorage.hasAppointment) {
        //    Lobibox.alert('warning', {
        //        title: 'Warning',
        //        msg: '<h3>Customer not found!</h3>',
        //        buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
        //        callback: function (lobibox, type) {
        //            Step1();
        //        }
        //    });
        //} else {
        //    AddNewCustomer();
        //}
    } else {
        if (customers.length == 1) {

            var customer = customers[0];

            Lobibox.alert('info', {
                title: 'Confirm',
                msg: '<h3>You are "' + customer.FullName + '"?</h3>',
                buttons: {
                    yes: {
                        'class': 'btn btn-success',
                        closeOnClick: true
                    },
                    no: {
                        'class': 'btn btn-warning',
                        closeOnClick: true
                    }
                },
                callback: function (lobibox, type) {
                    if (type === 'no') {
                        NoCustomer();
                    } else if (type === 'yes') {
                        HasAppointment(customer);

                        //if (_signInStorage.hasAppointment) {

                        //} else {
                        //    NoAppointment(customer);
                        //}
                    }
                }
            });
        } else {
            ClearModal();
            $('#modalCustomer').show();

            var cusHtml = "";
            cusHtml += '<div class="panel-heading">You are ...</div>' +
                '<div class="panel-body">';
            customers.forEach(function (v, i) {
                cusHtml += '<button type="button" class="btn-customer btn btn-default btn-lg btn-block" data-index="' + i + '">' + v.FullName + '</button>';
            });
            cusHtml += '<button type="button" class="btn btn-default text-exit btn-lg btn-block" onclick="return NoCustomer();">No</button>' +
                '</div>';
            $('#modalCustomer .panel').html(cusHtml);
            $('#modalCustomer .btn-customer').click(function () {
                var iIndex = $(this).data('index');
                HasAppointment(customers[iIndex]);
                //if (_signInStorage.hasAppointment) {
                //    HasAppointment(customers[iIndex]);
                //} else {
                //    NoAppointment(customers[iIndex]);
                //}
            });

        }
    }

    return false;

}

function NoCustomer() {

    if (_signInStorage.AllowDuplicatePhone) {
        AddNewCustomer();
    } else {
        Step1();
    }
}

function AddProduct(cid, pid, name, e) {

    CheckSaleItem(cid, pid, name);

    return false;
}

function CheckSaleItem(cid, pid, name) {

    UpdateSaleItem(cid, pid, name);
    return false;

    var hasCat = FindCategory(cid);
    var hasExist = FindSaleItems(pid);

    if (hasCat.Index > -1) {

        if (hasExist.Index == -1) {
            UpdateSaleItem(cid, pid, name);

            //var lobiboxDone = Lobibox.alert('info', {
            //    title: 'Messenger',
            //    msg: '<h3>Do you want replace service "' + hasCat.Data.NAME + '" to "' + name + '"?</h3>',
            //    buttons: {
            //        yes: {
            //            'class': 'btn btn-success',
            //            closeOnClick: true
            //        },
            //        no: {
            //            'class': 'btn btn-default',
            //            closeOnClick: true
            //        }
            //    },
            //    callback: function (lobibox, type) {
            //        ClearModal();

            //        if (type === 'yes') {

            //            _signInStorage.SaleItems.splice(hasCat.Index, 1);

            //            UpdateSaleItem(cid, pid, name);
            //        }
            //    }
            //});
        } else {
            UpdateSaleItem(cid, pid, name);
        }

    } else {
        UpdateSaleItem(cid, pid, name);
    }
    return false;
}

function UpdateSaleItem(cid, pid, name) {

    ClearModal();

    var hasExist = FindSaleItems(pid);
    if (hasExist.Index == -1) {
        _signInStorage.SaleItems.push({
            PID: pid,
            CID: cid,
            NAME: name,
            QTY: 1
        });

        $('.lobibox-backdrop,body > .lobibox').remove();

        var lobiboxDone = Lobibox.alert('info', {
            title: 'Messenger',
            msg: '<h3>Do you want to add more service?</h3>',
            buttons: {
                yes: {
                    'class': 'btn btn-success',
                    closeOnClick: true
                },
                no: {
                    'class': 'btn btn-default',
                    closeOnClick: true
                }
            },
            callback: function (lobibox, type) {

                ClearModal();


                if (type === 'yes') {
                    //ToggleServiceEmployee(0);
                } else {
                    if (isNoTechnician) {
                        _signInStorage.employeeCurrent = 0;
                        Complete();
                    } else {
                        ChooseEmployee();
                    }
                }
            }
        });

    } else {
        _signInStorage.SaleItems.splice(hasExist.Index, 1);
    }

    SetActiveSelected(false);
    ShowListSaleItems();

}

function RemoveSaleItem(pid) {
    var hasExist = FindSaleItems(pid);
    if (hasExist.Index > -1) {
        _signInStorage.SaleItems.splice(hasExist.Index, 1);
    }
    SetActiveSelected(false);
    ShowListSaleItems();
    $('#btnShowSaleItem').popover('show');
    ToggleServiceEmployee(false);
}

function ClearAllService() {

    ClearModal();

    _signInStorage.catCurrent = -1;
    _signInStorage.SaleItems = [];

    ToggleServiceEmployee(0);
    ShowListSaleItems();

    return false;
}

function ShowListSaleItems() {

    var content = '<ul class="list-group">';
    if (_signInStorage.SaleItems.length > 0) {
        $.each(_signInStorage.SaleItems, function (key, value) {
            content += '<li class="list-group-item">' + value.NAME + ' <button type="button" class="btn btn-xs btn-danger" onclick="return RemoveSaleItem(' + value.PID + ')"><i class="glyphicon glyphicon-trash"></i></button></li>';
        });
    } else {
        content += '<li class="list-group-item">Service is empty</li>';
    }
    content += '</ul>';

    $('.popover').remove();

    $('#btnShowSaleItem').popover('destroy');

    $('#btnShowSaleItem').data('content', content);

    $('#btnShowSaleItem').popover({
        html: true
    });

    if (_signInStorage.SaleItems.length > 0) {
        $('#btnShowSaleItem').html(_signInStorage.SaleItems.length + ' service <i class="glyphicon glyphicon-chevron-up"></i>');
    } else {
        $('#btnShowSaleItem').html('0 service');
    }

    return false;
}

function AddNewCustomer() {
    ClearModal();
    Loading();
    $.ajax({
        url: _url.AddNewCustomer,
        type: 'GET',
        success: function (respon) {
            RemoveLoading();

            $('#modalCustomer').show();

            $('#modalCustomer .panel').html(respon);

            $("#modalCustomer #Zip").mask("99999");

            $('#modalCustomer #Cell').val(_signInStorage.customerPhone);
            $('#modalCustomer #txtCell').html(_signInStorage.customerPhone);
            $('#modalCustomer #FirstName').focus();

            $('form#frmCustomer').attr("autocomplete", "off").attr("autocorrect", "off").attr("autocapitalize", "off");
            $('form#frmCustomer input').attr("autocomplete", "nope").attr("autocorrect", "off").attr("autocapitalize", "off");

            var validate = $("#frmCustomer").validate({
                errorClass: "help-block animation-slideDown",
                errorElement: "div",
                errorPlacement: function (e, a) {
                    a.parents(".form-group .col-sm-9").append(e), a.parents(".form-group .help-block").append(e)
                },
                highlight: function (e) {
                    $(e).closest(".form-group").removeClass("has-success has-error").addClass("has-error"),
                        $(e).closest(".help-block").remove()
                },
                success: function (e) {
                    e.closest(".form-group").removeClass("has-success has-error"),
                        e.closest(".help-block").remove()
                },
                rules: {
                    FirstName: { required: !0 },
                    LastName: { required: !0 },
                    Cell: { required: !0 }
                },
                submitHandler: function (form) {

                    Loading();

                    $.ajax({
                        url: $(form).attr('action') + '?ran=' + Math.random(),
                        type: 'POST',
                        data: $(form).serialize(),
                        dataType: 'json',
                        cache: false,
                        success: function (respon) {
                            RemoveLoading();
                            if (respon.status == true) {

                                _signInStorage.customerID = respon.customerID;

                                ChooseCategoryService();

                                ReloadCustomer(false);

                            } else {

                                Lobibox.alert('warning', {
                                    title: 'Warning',
                                    msg: '<h3>' + respon.msg + '</h3>',
                                    buttons: { yes: { 'class': 'btn btn-success', closeOnClick: true } },
                                    callback: function (lobibox, type) {
                                        Step2();
                                    }
                                });

                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {

                            RemoveLoading();

                            ShowError(xhr.status + ': ' + thrownError);
                        }
                    });

                    return false;
                }
            });
        },
        error: function (xhr, ajaxOptions, thrownError) {

            RemoveLoading();

            ShowError(xhr.status + ': ' + thrownError);

        }
    });
}

function CancelCustomer() {
    Step1();
}

function ChooseCategoryService() {

    $('#modalPhoneNumber,#modalCustomer').hide();

    $('#modalService').fadeIn();
    $('#modalService').css('opacity', 1);

    ToggleServiceEmployee(1);

    if (isNoService) {

        if (isNoTechnician) {

            _signInStorage.employeeCurrent = 0;

            Complete();

        } else {
            ChooseEmployee();
        }

        return false;
    }

    ChooseSaleItems();

    return false;

    Loading();

    $('#modalService').fadeIn();

    var catHtml = "";

    var iIndex = 0;

    $('#modalService .boxOrderCategory .row.saleCategories').height(_signInStorage.RowCats * 120);

    _signInStorage.Categories.forEach(function (v, i) {

        var topIndex = parseInt((v.Order - 1) / 3) * 120;
        var colIndex = (v.Order - 1) % 3;
        catHtml += '<div class="col col-' + colIndex + ' col-sm-4 col-xs-4" style="top:' + topIndex + 'px">' +
                        '<a href="javascript:;" class="cat-' + v.Id + '" onclick="return SelectedCatSaleItem(\'' + v.Id + '\', this);">' +
                            '<span class="bgColor" style="background:' + v.BackgroundColor + '"></span>' +
                            '<h3 style="color:' + v.ForeColor + ';">' +
                                '<span>' + v.Name + '</span>' +
                            '</h3>' +
                        '</a>' +
                    '</div>';
    });

    $('#modalService .boxOrderCategory .row.saleCategories').html(catHtml);

    $('#btnShowSaleItem').popover({
        html: true
    });

    ToggleServiceEmployee(0);

    RemoveLoading();

}

function SelectedCatSaleItem(id, e) {
    $('.boxOrderCategory a').removeClass('active');
    $('.boxOrderCategory a.cat-' + id).addClass('active');
    _signInStorage.catCurrent = id;
    ChooseSaleItems();
}

function ChooseSaleItems(catCurrent) {

    ClearModal();

    //var cid = _signInStorage.catCurrent;
    //var saleItems = FilterSaleItems(cid);


    Loading();

    var saleHtml = '';

    var iIndex = 0;

    $('.boxOrderProduct .saleItems').height(_signInStorage.RowItems * 120);

    _signInStorage.Categories.forEach(function (c, i) {

        var cid = c.Id;

        var saleItems = FilterSaleItems(cid);

        saleHtml += "<div class='clearfix text-center'><h2>" + c.Name + "</h2></div>";

        var maxHeight = 120;

        var saleItemHtml = "";
        saleItems.forEach(function (v, i) {

            var topIndex = parseInt((v.Order - 1) / 3) * 120;

            var colIndex = (v.Order - 1) % 3;

            if (maxHeight < (topIndex + 120)) {
                maxHeight = topIndex + 120;
            }

            var price = '';
            if (v.DisplayPrice) {
                price = '<span class="price">' + v.Price + '</span>';
            }

            var bgImage = '';
            if (v.Path != null) {
                bgImage = v.Path;
                if (bgImage.indexOf('data:image/') == -1) {
                    bgImage = 'data:image/png;base64,' + bgImage;
                }
                bgImage = '<span class="bgImage" style="background:url(\'' + bgImage + '\');"></span>';
            }

            saleItemHtml += '<div class="col col-' + colIndex + ' col-sm-4 col-xs-4" style="top:' + topIndex + 'px">' +
                            '<a href="javascript:;" class="p-' + v.Id + '" onclick="return AddProduct(' + cid + ',' + v.Id + ', \'' + v.Name + '\', this);">' +
                                '<span class="bgColor" style="background:' + v.BackgroundColor + '"></span>' +
                                bgImage + price +
                                '<span class="time">' + v.WorkTime + '</span>' +
                                '<span class="name" style="color:' + v.ForeColor + '">' + v.Name + '</span>' +
                            '</a>' +
                        '</div>';
        });

        saleHtml += "<div class='row' style='height:" + (maxHeight + 50) + "px'>";

        saleHtml += saleItemHtml;

        saleHtml += "</div>";
    });


    $('.boxOrderProduct .saleItems').html(saleHtml);

    ToggleServiceEmployee(1);

    SetActiveSelected(true);

    RemoveLoading();

    return false;
}

function SetActiveSelected(isLoad) {
    $('.boxOrderProduct .row .col.active, .boxOrderProduct .row a.active').removeClass('active');
    $('.boxOrderProduct .row a span.qty').html('');
    _signInStorage.SaleItems.forEach(function (element, index) {
        $('.boxOrderProduct .row a.p-' + element.PID).addClass('active');
        $('.boxOrderProduct .row a.p-' + element.PID).parents('.col').addClass('active');
    });
}

function ToggleServiceEmployee(iIndex) {

    ClearModal();

    if (iIndex == 0) {
        $('.boxOrderCategory').show();
        $('.boxOrderProduct').hide();
        $('.boxEmployee').hide();
        $('#btnChooseEmployee').show();
        ToggleServiceEmployee(1);
    } else if (iIndex == 1) {
        $('.boxOrderCategory').hide();
        $('.boxOrderProduct').show();
        $('.boxEmployee').hide();
        $('#btnChooseEmployee').show();
    } else if (iIndex == 2) {
        $('.boxOrderCategory').hide();
        $('.boxOrderProduct').hide();
        $('.boxEmployee').show();
        $('#btnChooseEmployee').hide();
    }
}

function HasAppointment(customer) {

    Loading();

    var appointments = FilterAppointment(customer.ID);

    RemoveLoading();

    if (appointments.length == 0) {
        //Lobibox.alert('warning', {
        //    title: 'Warning',
        //    msg: '<h3>Appointment not found!</h3>',
        //    buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
        //    callback: function (lobibox, type) {
        //        Step1();
        //    }
        //});
        NoAppointment(customer);
    } else {
        CompleteAppointment(appointments[0].Id, customer.ID);

        //if (appointments.length == 1) {

        //    CompleteAppointment(appointments[0].Id);

        //} else {
        //    ClearModal();
        //    $('#modalCustomer').show();

        //    var appHtml = "";
        //    appHtml += '<div class="panel-heading">Your appointment ...</div>' +
        //                    '<div class="panel-body">';
        //    appointments.forEach(function (v, i) {
        //        var technician = "";
        //        if (v.Details != null && v.Details.length > 0) {
        //            technician = ' - Request: ' + v.Details[0].Technician;
        //        }
        //        appHtml += '<button type="button" class="btn-appointment btn btn-default btn-lg btn-block" data-index="' + i + '">' + v.StartDate + ' - ' + v.EndDate + technician + '</button>';
        //    });
        //    appHtml += '<button type="button" class="btn btn-noappointment btn-default text-exit btn-lg btn-block" Onclick="return Step1();">No, Cancel</button>' +
        //                '</div>';
        //    $('#modalCustomer .panel').html(appHtml);
        //    $('#modalCustomer .btn-appointment').click(function () {
        //        var iIndex = $(this).data('index');
        //        CompleteAppointment(appointments[iIndex].Id);
        //    });
        //    //$('#modalCustomer .btn-appointment').click(function () {
        //    //    NoAppointment(customer);
        //    //});

        //}
    }

    return false;
}

function NoAppointment(customer) {
    _signInStorage.customerID = customer.ID;
    ChooseCategoryService();
    return false;
}

function ChooseEmployee() {


    if (isNoService == false && _signInStorage.SaleItems.length == 0) {
        var lobiboxDone = Lobibox.alert('warning', {
            title: 'Service is empty',
            msg: '<h3>Please choose service</h3>',
            buttons: {
                yes: {
                    'class': 'btn btn-default',
                    closeOnClick: true,
                    text: 'OK (<span class="lblSecondCountdown">10</span>)'
                }
            },
            callback: function (lobibox, type) {
                clearInterval(intervalDone);
                ClearModal();
            }
        });

        var intervalDone = StartCountDown(function () {
            clearInterval(intervalDone);
            lobiboxDone.hide();
            ClearModal();
        }, 9);
        return false;
    }
    var sID = $.map(_signInStorage.SaleItems, function (val, i) { return val.PID + '' });

    Loading();

    var technicians = FilterTechnician(sID);

    RemoveLoading();

    if (isNoService) {
        technicians = _signInStorage.Technicians;
    }

    if (technicians.length == 0) {
        _signInStorage.employeeCurrent = 0;
        Complete();
        return false;
    }

    ShowListSaleItems();

    var noImage = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAACl0lEQVRoQ+2YT27aQBTGvxd7X67QE9Q5QWFTCRTUcALMDZoFVGqTNm1QF1ApvUGcE5AKlEjdxDlByQlyBXePeZUHLJI0xva8IciqvfX8+X7fezPzZggF/6jg+lECbDuCZQQeR4Cv9qoAtcHsgMhR/5mnIJoCfE71iW8yasYiwL8aDsKdU4Cq6wWyD2t+QG8upyZAjAAo15lGIFQyiWIEsMOaCQgxgHJ+Zl1nFh8TGoKQA1w2fRBeZ3L+n0bsU31S0+u76CUCWC7Ya4kAgGuShS0EaHoA2jIAnFN97OqOIQTYmwL0SnfyeIulxmRXdwwhQJN1J77fj+pjbR3aHdX5dFV4AAMpBL6l+mRxYmt80ggUfhFHdU9xt1G1DiQHGeOGGuOU2ml9XolSSAGoIs6KKswXOVP4D6ywKq2HxACL3UiV0Bc5IIyIF5cS9x1fFnU/Uusixg3s8J3U+XhuIxF4ALKIhguwszql+RZQFxpPUvc8laLGAXKuA3HzEkBsoXAAYxHofBq+5TmikmC5r3PlwaUeFCy1+rSD6dnX7k+hdtVdBND5+L3NNN8HqYt8tvvwSnUAZj96qfD676MtWOvTAnAPh5Hgz6DYba25V50Y0UH4xet3cz+55AJwj08rmM2i1wfR8Z+IG4HYdss7PojTLdWZzADKdcJII1VSRTxqEIDRyhqNTADu0cAF6CyvEll77ngnvahcX/ulAmxHfKw5HWItgPth4MCi32kubPR/yLvet17iM2QigFqw4ezuGXI+jT+AZb9MWtjJAIeDEYj200Z/lv/MF16/18pVzLlHQyNPJqYAvZPuk2YnR6AEMOX9YpwyAmb9zD/a/xeB/B5tp0dqKbEdWdlnLQGye7WZlmUENuNr9lH/AieV6jH9+YyqAAAAAElFTkSuQmCC';

    var techHtml = '<div class="col-lg-2 col-md-3 col-sm-4 col-xs-6 text-center">' +
                        '<button type="button" data-id="0" class="btn btn-success">' +
                            '<span class="bgColor" style="background:#81f765"></span>' +
                            '<span class="bgImage nosize" style="background:url(\'' + noImage + '\');"></span>' +
                            '<span class="name">' +
                                'First Available<br />Technician' +
                            '</span>' +
                        '</button>' +
                    '</div>';

    technicians.forEach(function (v, i) {

        bgImage = '';
        if (v.Path != null) {
            bgImage = v.Path;
            if (bgImage.indexOf('data:image/') == -1) {
                bgImage = 'data:image/png;base64,' + bgImage;
            }
            if (bgImage == noImage) {
                bgImage = '<span class="bgImage nosize" style="background:url(\'' + bgImage + '\');"></span>';
            } else {
                bgImage = '<span class="bgImage" style="background:url(\'' + bgImage + '\');"></span>';
            }
        } else {
            bgImage = '<span class="bgImage nosize" style="background:url(\'/Content/view/img/no-image.png\');"></span>';
        }

        var displayName = v.FullName;
        if (v.DisplayNickName == "fullname") {
            if (v.NickName != '') {
                displayName += '<br>(' + v.NickName + ')';
            }
        } else if (v.DisplayNickName == "name") {
            if (v.NickName != '') {
                displayName = v.NickName;
            } else {
                displayName = v.FullName;
            }
        }

        techHtml += '<div class="col-lg-2 col-md-3 col-sm-4 col-xs-6 text-center">' +
                        '<button type="button" data-id="' + v.Id + '" class="btn btn-default">' +
                            '<span class="bgColor" style="background:' + v.BackgroundColor + '"></span>' +
                            bgImage +
                            '<span class="name" style="color:' + v.ForeColor + '">' +
                                displayName +
                            '</span>' +
                        '</button>' +
                    '</div>';
    });

    $('.boxEmployee #employeeList').html(techHtml);

    ToggleServiceEmployee(2);

    $('.boxEmployee #employeeList button').click(function () {
        var employeeID = parseFloat($(this).data('id'));
        _signInStorage.employeeCurrent = employeeID;

        Complete();

        return false;
    });

    return false;

}

function Complete() {

    var sID = $.map(_signInStorage.SaleItems, function (val, i) { return val.PID }).join(',');

    Loading();

    $.ajax({
        url: _url.Complete,
        type: 'POST',
        data: {
            sID: sID,
            eID: _signInStorage.employeeCurrent,
            cID: _signInStorage.customerID,
            noService: isNoService ? 'true' : 'false',
            noTechnician: isNoTechnician ? 'true' : 'false'
        },
        success: function (respon) {
            RemoveLoading();

            $('#modalService').hide();

            if (respon.status) {

                _signInStorage.hasAppointment = false;
                _signInStorage.customerPhone = '';
                _signInStorage.customerName = '';
                _signInStorage.customerID = 0;
                _signInStorage.stepCurrent = 0;
                _signInStorage.catCurrent = -1;
                _signInStorage.employeeCurrent = -1;
                _signInStorage.SaleItems = [];

                var lobiboxDone = Lobibox.alert('success', {
                    title: 'Thank you!',
                    msg: '<h3>Hello, ' + respon.customerName + ' please have a seat and we\'ll be right with you</h3>',
                    buttons: {
                        yes: {
                            'class': 'btn btn-success',
                            closeOnClick: true,
                            text: 'Will auto close in <span class="lblSecondCountdown">30</span> second'
                        }
                    },
                    callback: function (lobibox, type) {
                        clearInterval(intervalDone);
                        Step1();
                    }
                });

                var intervalDone = StartCountDown(function () {
                    clearInterval(intervalDone);
                    lobiboxDone.hide();
                    Step1();
                });
            } else {
                if (respon.msg === 'no_service') {
                    Lobibox.alert('warning', {
                        title: 'Warning',
                        msg: '<h3>Please select service.</h3>',
                        buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
                        callback: function (lobibox, type) {
                            Step2();
                        }
                    });
                } else if (respon.msg === 'customer') {
                    Lobibox.alert('warning', {
                        title: 'Warning',
                        msg: '<h3>Customer not found!</h3>',
                        buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
                        callback: function (lobibox, type) {
                            Step2();
                        }
                    });
                } else {
                    ShowError(respon.msg, function () { });
                }
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {

            RemoveLoading();

            ShowListSaleItems();

            ShowError(xhr.status + ': ' + thrownError, function () {

            });
        }
    });
    return false;

}

function CompleteAppointment(appID, cusID) {

    $('#modalCustomer .panel').html('');
    $('#modalCustomer').hide();

    Loading();

    $.ajax({
        url: _url.CompleteAppointment,
        type: 'POST',
        data: {
            appID: appID,
            cusID: cusID
        },
        success: function (respon) {
            RemoveLoading();

            $('#modalService').hide();

            if (respon.status) {

                var lobiboxDone = Lobibox.alert('success', {
                    title: 'Thank you!',
                    msg: '<h3>' + respon.customerName + ' please have a seat and we\'ll be right with you</h3>',
                    buttons: {
                        yes: {
                            'class': 'btn btn-success',
                            closeOnClick: true,
                            text: 'Will auto close in <span class="lblSecondCountdown">30</span> second'
                        }
                    },
                    callback: function (lobibox, type) {
                        clearInterval(intervalDone);
                        Step1();
                    }
                });

                var intervalDone = StartCountDown(function () {
                    clearInterval(intervalDone);
                    lobiboxDone.hide();
                    Step1();
                });

            } else {
                if (respon.msg === 'customer') {
                    Lobibox.alert('warning', {
                        title: 'Warning',
                        msg: '<h3>Customer not found!</h3>',
                        buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
                        callback: function (lobibox, type) {
                            Step2();
                        }
                    });
                } else if (respon.msg === 'appointment') {
                    Lobibox.alert('warning', {
                        title: 'Warning',
                        msg: '<h3>Appointment not found!</h3>',
                        buttons: { ok: { 'class': 'btn btn-default', closeOnClick: true, text: 'OK' } },
                        callback: function (lobibox, type) {
                            Step1();
                        }
                    });
                } else {
                    Step1();
                }
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {

            RemoveLoading();

            ShowError(xhr.status + ': ' + thrownError);
        }
    });
    return false;

}

function StartCountDown(callBack, time) {
    var counter = 29;
    if (time != null) {
        counter = time;
    }
    return setInterval(function () {
        $('.lblSecondCountdown').html(counter);
        counter--;
        if (counter < 0) {
            if (typeof (callBack) === 'function') {
                callBack();
            }
        }
    }, 1000);
}

function ShowError(msg, callback) {
    var lobiboxError = Lobibox.alert('error', {
        title: 'Error',
        msg: '<h3>' + msg + '</h3>',
        buttons: {
            yes: {
                'class': 'btn btn-default', closeOnClick: true,
                text: 'OK. Will auto close in <span class="lblSecondCountdown">30</span> second'
            }
        },
        callback: function (lobibox, type) {
            clearInterval(intervalError);
            if (callback == null) {
                Step1();
            } else if (typeof (callback) === 'function') {
                callback();
            }
        }
    });

    var intervalError = StartCountDown(function () {
        clearInterval(intervalError);
        lobiboxError.hide();
        if (callback == null) {
            Step1();
        } else if (typeof (callback) === 'function') {
            callback();
        }
    });
}

String.prototype.replaceAll = function (n, t) {
    for (var i = this, r = i.indexOf(n) ; r != -1;) i = i.replace(n, t),
     r = i.indexOf(n);
    return i
};

jQuery.fn.modalPhone = function (options) {

    var _self = this;
    _self.valueCurrent = "";
    _self.find('.boxDisplayNumber label').html("___-___-____");

    _self.show();
    $('#modalCustomer,#modalService').hide();

    var defaults = {
        fullRequired: false,
        complete: function () { },
        exit: function () { }
    };

    var settings = $.extend({}, defaults, options);

    var el = [_self.find('.btnPhoneEnter'),
                _self.find('.btnPhoneExit'),
                _self.find('.btnPhoneClear'),
                _self.find('.boxCellNumber button.btn-cell-number'),
                _self.find('.boxDisplayNumber label'),
                $("#txtPhone")];

    el[5].mask("999-999-9999");
    el[5].focus();


    el[5].keyup(function () {
        if (_self.GetPhone().length == 10) {
            el[0].click();
        }
    });

    el[0].click(function () {
        if (settings.fullRequired) {
            if (_self.GetPhone().length != 10) {
                alert("Phone number invalid!");
                el[5].focus();
                //Lobibox.alert("warning", { msg: "Phone number invalid!" });
                return false;
            }
        }
        _self.Destroy();
        settings.complete.call(null, _self);
    });
    el[1].click(function () {
        _self.Destroy();
        settings.exit.call(null, _self);
    });

    el[2].click(function () {
        el[5].val('');
        el[5].focus();
    });

    _self.Destroy = function () {
        for (i = 0; i < el.length; i++)
            el[i].unbind("click");
        _self.hide();
    }

    _self.GetPhone = function () {
        return el[5].val().replaceAll('-', '').replaceAll('_', '');
    }

    _self.ShowPhone = function () {
        el[4].html(_self.GetPhoneFormat);
    }

    _self.GetPhoneFormat = function () {
        return el[5].val();
    }

    _self.GetPhoneFormatServer = function () {
        var phone = (el[5].val() + '-').replaceAll('-', '');
        var str = "__________";
        phone += str.substring(phone.length, 10);

        var match = phone.match(/^([0-9_]{3})([0-9_]{3})([0-9_]{4})$/);
        if (match) {
            return '(' + match[1] + ') ' + match[2] + '-' + match[3]
        }
        return null
    }

    return _self;
};
