
function InitFirst() {

    //Loading();

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

}

function Loading() {
    $('.loading-modal').remove();
    $('body').append('<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;

}

function CheckSalary() {
    $('#step1').hide();
    ClearModal();
    _signInStorage.stepCurrent = 4;
    $("#txtPhone").val('');
    $("#txtPhone").focus();
    $('#modalPhoneNumber').modalPassCode({
        fullRequired: true,
        complete: function (e) {
            $('#modalPhoneNumber').hide();
            _signInStorage.passCode = e.GetPhoneFormatServer();
            CheckPassCodeViewSalary();
        },
        exit: function () {
            Step1();
        }
    });
    return false;
}

let dateFrom = new Date();
let dateTo = new Date();

function CheckPassCodeViewSalary() {

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

    Loading();

    $.ajax({
        url: _url.CheckPassCode,
        type: 'POST',
        dataType: 'JSON',
        data: {
            passcode: _signInStorage.passCode
        },
        success: function (respon) {

            RemoveLoading();

            if (respon.status) {

                _signInStorage.employeeCurrent = respon.employeeID;

                $('#modalCustomer .panel-heading').html('Salary Report: ' + respon.employeeName);

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

                $('#txtDateFrom').datetimepicker({
                    format: 'MM/DD/YYYY',
                    calendarWeeks: true
                });
                $('#txtDateTo').datetimepicker({
                    format: 'MM/DD/YYYY',
                    calendarWeeks: true
                });
                $("#txtDateFrom").on("dp.change", function (e) {
                    $('#txtDateTo').data("DateTimePicker").minDate(e.date);
                });
                $("#txtDateTo").on("dp.change", function (e) {
                    $('#txtDateFrom').data("DateTimePicker").maxDate(e.date);
                });


                setTimeout("currentWeekly();", 300);

            } else {
                Lobibox.alert('warning', {
                    title: 'Warning',
                    msg: '<h3>You are entering WRONG security code or ID. Please enter again..</h3>',
                    buttons: { yes: { 'class': 'btn btn-success', closeOnClick: true } },
                    callback: function (lobibox, type) {
                        CheckSalary();
                    }
                });
            }

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


    return false;

}



function prevDate() {
    dateFrom = new Date(dateFrom.addDays(-1));
    dateTo = new Date(dateFrom);

    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);
    $('#txtDateTo').data("DateTimePicker").date(dateTo);

    ReportSalary();

}
function nextDate() {

    dateFrom = new Date(dateFrom.addDays(1));
    dateTo = new Date(dateFrom);

    $('#txtDateTo').data("DateTimePicker").date(dateTo);
    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);

    ReportSalary();

}
function currentDate() {
    $('.box-date-range').hide();
    $('#btnPrevDate,#btnNextDate').prop('disabled', false);
    $('#btnPrevWeekly,#btnNextWeekly').prop('disabled', true);
    $('#btnCurrDate').removeClass('btn-default').addClass('btn-primary');
    $('#btnCurrWeekly').addClass('btn-default').removeClass('btn-primary');
    $('#btnDateRange').addClass('btn-default').removeClass('btn-primary');

    dateFrom = new Date();
    dateTo = new Date();

    $('#txtDateTo').data("DateTimePicker").date(dateTo);
    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);

    ReportSalary();
}

function prevWeekly() {

    dateFrom = new Date(dateFrom.addDays(-3)).getFirstDayOfWeek(0);
    dateTo = new Date(dateFrom).getLastDayOfWeek(0);

    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);
    $('#txtDateTo').data("DateTimePicker").date(dateTo);

    ReportSalary();

}
function nextWeekly() {

    dateFrom = new Date(dateTo.addDays(3)).getFirstDayOfWeek(0);
    dateTo = new Date(dateFrom).getLastDayOfWeek(0);

    $('#txtDateTo').data("DateTimePicker").date(dateTo);
    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);

    ReportSalary();

}
function currentWeekly() {
    $('.box-date-range').hide();
    $('#btnPrevDate,#btnNextDate').prop('disabled', true);
    $('#btnPrevWeekly,#btnNextWeekly').prop('disabled', false);
    $('#btnCurrWeekly').removeClass('btn-default').addClass('btn-primary');
    $('#btnCurrDate').addClass('btn-default').removeClass('btn-primary');
    $('#btnDateRange').addClass('btn-default').removeClass('btn-primary');

    dateFrom = new Date().getFirstDayOfWeek(0);
    dateTo = new Date(dateFrom).getLastDayOfWeek(0);

    console.log(dateFrom, dateTo);

    $('#txtDateFrom').data("DateTimePicker").date(dateFrom);
    $('#txtDateTo').data("DateTimePicker").date(dateTo);

    ReportSalary();
}

function dateRange() {
    $('.box-date-range').show();
    $('#btnPrevDate,#btnNextDate').prop('disabled', true);
    $('#btnPrevWeekly,#btnNextWeekly').prop('disabled', true);
    $('#btnCurrDate').addClass('btn-default').removeClass('btn-primary');
    $('#btnCurrWeekly').addClass('btn-default').removeClass('btn-primary');
    $('#btnDateRange').removeClass('btn-default').addClass('btn-primary');
}

function ReportSalary() {

    if ($('#txtDateFrom').data('DateTimePicker').date() == null) {
        $('#txtDateFrom').focus();
        return false;
    }
    if ($('#txtDateTo').data('DateTimePicker').date() == null) {
        $('#txtDateTo').focus();
        return false;
    }

    Loading();

    let dateFrom = moment($('#txtDateFrom').data('DateTimePicker').date()).format('DD/MM/YYYY');
    let dateTo = moment($('#txtDateTo').data('DateTimePicker').date()).format('DD/MM/YYYY');

    $.ajax({
        url: _url.EmployeeSalary,
        type: 'POST',
        data: {
            employeeID: _signInStorage.employeeCurrent,
            from: dateFrom,
            to: dateTo
        },
        success: function (respon) {


            RemoveLoading();

            $('#modalCustomer .panel-body .boxSalary').html(respon);
            $('.boxSalary').scrollTop(0);
        },
        error: function (xhr, ajaxOptions, thrownError) {
        }
    });


    return false;

}

function ClockInOut(stepNumer) {
    $('#step1').hide();
    ClearModal();
    _signInStorage.stepCurrent = stepNumer;
    $("#txtPhone").val('');
    $("#txtPhone").focus();
    $('#modalPhoneNumber').modalPassCode({
        fullRequired: true,
        complete: function (e) {
            $('#modalPhoneNumber').hide();
            _signInStorage.passCode = e.GetPhoneFormatServer();
            CheckPassCodeClockInOut();
        },
        exit: function () {
            Step1();
        }
    });
    return false;
}

function CheckPassCodeClockInOut() {

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

    Loading();

    let url = '';

    if (_signInStorage.stepCurrent == 2) {
        url = _url.EmployeeClockIn;
    } else if (_signInStorage.stepCurrent == 3) {
        url = _url.EmployeeClockOut;
    }

    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'JSON',
        data: {
            passcode: _signInStorage.passCode
        },
        success: function (respon) {

            RemoveLoading();

            if (respon.status) {
                Lobibox.alert(respon.classStatus, {
                    title: _signInStorage.stepCurrent == 2 ? 'Clock In' : 'Clock Out',
                    msg: respon.msg,
                    buttons: { yes: { 'class': 'btn btn-success', closeOnClick: true } },
                    callback: function (lobibox, type) {
                        Step1();
                    }
                });
            } else {
                Lobibox.alert('warning', {
                    title: 'Warning',
                    msg: '<h3>You are entering WRONG security code or ID. Please enter again..</h3>',
                    buttons: { yes: { 'class': 'btn btn-success', closeOnClick: true } },
                    callback: function (lobibox, type) {
                        if (_signInStorage.stepCurrent == 2) {
                            ClockInOut(2);
                        } else if (_signInStorage.stepCurrent == 3) {
                            ClockInOut(3);
                        }
                    }
                });
            }

        },
        error: function (xhr, ajaxOptions, 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.modalPassCode = 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].focus();


    el[5].keyup(function (e) {
        if (_self.GetPhone().length > 0) {
            if (e.key == 'Enter' || e.keyCode == 13 || e.which == 13) {
                el[0].click();
            } else if (_self.GetPhone().length == 10) {
                el[0].click();
            }
        }
    });

    el[0].click(function () {
        if (settings.fullRequired) {
            if (_self.GetPhone().length == 0) {
                alert("Please enter Your Pass Code!");
                el[5].focus();
                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('-', '');
        return phone
    }

    return _self;
};

Date.prototype.addDays = function (days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

Date.prototype.getFirstDayOfWeek = function (d) {
    if (d >= 0) {
        var next = this;
        next.setDate(this.getDate() - (this.getDay() || 7) - d);
        return next;
    }
}
Date.prototype.getLastDayOfWeek = function (d) {
    if (d >= 0) {
        var next = this;
        next.setDate(this.getDate() - this.getDay() + 6 + d);
        return next;
    }
}