$(document).ready(function () {
    //Initialize Select2 Elements
    $('.select2bs4').select2({
        theme: 'bootstrap4'
    });

	$('[data-toggle="tooltip"]').tooltip()
});



jQuery(function ($) { // DOM ready and $ alias secured

    $('#activity').on('input', function (e) {
        Activity_Suggestions();
    });
});

var tableRow_count = 0;
function addToTable() {
    if (tableRow_count == 8) {
        return false;
    }
    var activity = $('#activity').val().trim();
    var frequent = $('#frequent').val().trim();
    var times = $('#times').val().trim();
    var hour = $('#hour').val().trim();
    var satisfaction = $('#satisfaction').val().trim();
    if (activity == "" || activity == null || frequent == "" || frequent == null || times == "" || times == null || hour == "" || hour == null || satisfaction == "" || satisfaction == null) {
        toastsCall('bg-danger', 'Error', 'All fields are required !');
        return false;
    }

	var targetText = $('#targetText').val().trim();
	var targetSatisfaction = $('#targetSatisfaction').val().trim();
	var targetMonitor = $('#targetMonitor').val().trim();
	var monitorFrequent = $('#monitorFrequent').val().trim();
	var suggestion = $('#suggestion').val().trim();

    var timetxt = "time"
    if (times > 1) {
        timetxt = "times"
    }


    var html = "<tr><td> " + activity + "<br>" + frequent + " / " + times + " " + timetxt + " / " + hour + "/ Satisfaction level - " + satisfaction + "" +
		"<br> Target - "+targetText+"/"+targetSatisfaction+"/"+targetMonitor+"/"+monitorFrequent+"/"+suggestion+"</td>" +
            "<td><i style='cursor: pointer'  onclick='removeRow(this);' class='fas fa-window-close'></i>" +
            "<input type='hidden' name='activityArr[]' value='" + activity + "'>" +
            "<input type='hidden' name='frequentArr[]' value='" + frequent + "'>" +
            "<input type='hidden' name='timeArr[]' value='" + times + "'>" +
            "<input type='hidden' name='hourArr[]' value='" + hour + "'>" +
            "<input type='hidden' name='satisfactionArr[]' value='" + satisfaction + "'>" +
            "<input type='hidden' name='targetTextArr[]' value='" + targetText + "'>" +
            "<input type='hidden' name='targetSatisfactionArr[]' value='" + targetSatisfaction + "'>" +
            "<input type='hidden' name='targetMonitorArr[]' value='" + targetMonitor + "'>" +
            "<input type='hidden' name='monitorFrequentArr[]' value='" + monitorFrequent + "'>" +
            "<input type='hidden' name='suggestionArr[]' value='" + suggestion + "'>" +
            "</td><tr>";
    $("#tbody_div").append(html);
    tableRow_count++;
    $("#count").html("(" + tableRow_count + "/8)");
    if (tableRow_count === 8) {
        $('html, body').animate({scrollTop: $(document).height()}, 'fast');
    } else {
        $("#activity").focus();
    }
    $('#activity').val('');
    $('#frequent').val('Daily');
    $('#times').val(1);
    $('#hour').val("");
    $("#satisfaction").val('');
	$('#targetText').val('');
	$('#targetMonitor').val('');
	$('#suggestion').val('');
	onChnageTarget();
	onChangeTartgetMonitor();

}


function removeRow(btndel) {
    if (typeof (btndel) == "object") {
        $(btndel).closest("tr").remove();
        tableRow_count--;
        $("#count").html("(" + tableRow_count + "/8)");
    } else {
        return false;
    }
}

function Activity_Suggestions() {
    var keyword = $("#activity").val().trim();
    if (keyword.length < 2) {
        return true;
    }
    if (keyword == "" || keyword == null) {
        return false;
    }
    $.ajax({
        url: base_urlJs+"Public_Controller/Activity_Suggestions",
        type: "post",
        data: {Key: keyword},
        success: function (data) {
            var activityList = [];
            var arr = JSON.parse(data);
            for (i = 0; i < arr.length; i++) {
                if (arr[i]['activity'] != "") {
                    activityList.push(arr[i]['activity']);
                }
            }
            $("#activity").autocomplete({
                source: activityList
            });
        },
        error: function (jqXhr) {
            if (jqXhr.status == 400) { //Validation error or other reason for Bad Request 400
                var json = $.parseJSON(jqXhr.responseText);
                console.log(json);
            }
        }
    });
}


function validateUserData() {

    var empName = $("#empName").val().trim();
    var designation = $("#designation").val().trim();
    var empID = $("#empID").val().trim();
    var department = $("#department").val().trim();
    var supervisor = $("#supervisor").val().trim();
    var duration = $("#duration").val().trim();
    if (empName === "" || empName === null) {
        toastsCall('bg-danger', 'Error', 'Name is required !');
        return false;
    }
      if (designation === "" || designation === null) {
        toastsCall('bg-danger', 'Error', 'Designation is required !');
        return false;
    }
    if (empID === "" || empID === null) {
        toastsCall('bg-danger', 'Error', 'EmpID is required !');
        return false;
    }

    if (department === "" || department === null) {
        toastsCall('bg-danger', 'Error', 'Department is required !');
        return false;
    }

    if (supervisor === "" || supervisor === null) {
        toastsCall('bg-danger', 'Error', 'Supervisor is required !');
        return false;
    }

    if (duration === "" || duration === null) {
        toastsCall('bg-danger', 'Error', 'Duration is required !');
        return false;
    }



    validateEmpID(empID);
}

function validateEmpID(empID) {
    HoldOn.open({
        theme: "sk-bounce",
        message: "Please wait...."
    });
    $.ajax({
        url: base_urlJs+"Public_Controller/validate_empID",
        type: "post",
        data: {empId: empID},
        success: function (data) {
            var st = JSON.parse(data);
            if (st) {
                toastsCall('bg-success', 'Success', 'Please add your activities !');
                $("#user_dataForm").hide();
                $("#activity_form").show();
            } else {
                toastsCall('bg-danger', 'Error', 'Emp Id is alredy registerd !');
            }
            HoldOn.close();
        },
        error: function (jqXhr) {
            if (jqXhr.status == 400) { //Validation error or other reason for Bad Request 400
                var json = $.parseJSON(jqXhr.responseText);
                HoldOn.close();
                toastsCall('bg-danger', 'Error', 'Internal Server Error!');
            }
        }
    });
}

function submitForm() {
    if (tableRow_count < 1) {
        toastsCall('bg-danger', 'Error', 'Please add at lesat one activity !');
        console.log(tableRow_count);
        return false;
    }

    var empName = $("#empName").val().trim();
    var designation = $("#designation").val().trim();
    var empID = $("#empID").val().trim();
    var department = $("#department").val().trim();
    var supervisor = $("#supervisor").val().trim();
    var duration = $("#duration").val().trim();
    if (empName === "" || empName === null) {
        toastsCall('bg-danger', 'Error', 'Name is required !');
        $("#activity_form").hide();
        $("#user_dataForm").show();
        return false;
    }
    if (designation === "" || designation === null) {
        toastsCall('bg-danger', 'Error', 'Designation is required !');
        $("#activity_form").hide();
        $("#user_dataForm").show();
        return false;
    }
    if (empID === "" || empID === null) {
        toastsCall('bg-danger', 'Error', 'EmpID is required !');
        $("#activity_form").hide();
        $("#user_dataForm").show();
        return false;
    }

    if (department === "" || department === null) {
        toastsCall('bg-danger', 'Error', 'Department is required !');
        $("#activity_form").hide();
        $("#user_dataForm").show();
        return false;
    }

    if (supervisor === "" || supervisor === null) {
        toastsCall('bg-danger', 'Error', 'Supervisor is required !');
        return false;
    }

    if (duration === "" || duration === null) {
        toastsCall('bg-danger', 'Error', 'Duration is required !');
        $("#activity_form").hide();
        $("#user_dataForm").show();
        return false;
    }
    var frequentArr = $("input[name='frequentArr[]']").map(function () {
        return $(this).val().trim();
    }).get();
    var timeArr = $("input[name='timeArr[]']").map(function () {
        return $(this).val().trim();
    }).get();
    var activityarr = $("input[name='activityArr[]']").map(function () {
        return $(this).val().trim();
    }).get();
    var hourArr = $("input[name='hourArr[]']").map(function () {
        return $(this).val().trim();
    }).get();
    var satisfactionArr = $("input[name='satisfactionArr[]']").map(function () {
        return $(this).val();
    }).get();

    var targetTextArr = $("input[name='targetTextArr[]']").map(function () {
        return $(this).val();
    }).get();
    var targetSatisfactionArr = $("input[name='targetSatisfactionArr[]']").map(function () {
        return $(this).val();
    }).get();
    var targetMonitorArr = $("input[name='targetMonitorArr[]']").map(function () {
        return $(this).val();
    }).get();
    var monitorFrequentArr = $("input[name='monitorFrequentArr[]']").map(function () {
        return $(this).val();
    }).get();
    var suggestionArr = $("input[name='suggestionArr[]']").map(function () {
        return $(this).val();
    }).get();

    var dataarr = {
        'empName': empName,
        'designation': designation,
        'empID': empID,
        'department': department,
        'supervisor': supervisor,
        'duration': duration,
        'frequentArr': frequentArr,
        'activityarr': activityarr,
        'timeArr': timeArr,
        'satisfactionArr': satisfactionArr,
        'hourArr': hourArr,
		'targetTextArr':targetTextArr,
		'targetSatisfactionArr':targetSatisfactionArr,
		'targetMonitorArr':targetMonitorArr,
		'monitorFrequentArr':monitorFrequentArr,
		'suggestionArr':suggestionArr,

	};
    Swal.fire({
    title: 'Do you want do submit?',
            text: "You won't be able to change after submit,Please double check your activities !",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes'
    }).then((result) => {
    if (result.value) {
        HoldOn.open({
            theme: "sk-bounce",
            message: "Please wait...."
        });
        $.ajax({
            url: base_urlJs+"Public_Controller/addEmpActivity",
            type: "post",
            data: dataarr,
            success: function (data) {
                var st = JSON.parse(data);
                HoldOn.close();
                if (st) {
                    Swal.fire(
                            'Success!',
                            'Your Activities successfully Recorded.',
                            'success'
                            );
                    $("#empName").val('');
                    $("#designation").val('');
                    $("#empID").val('');
                    $("#department").val('');
                    $("#supervisor").val('');
                    $("#duration").val('');
                    $('.select2bs4').select2({
                        theme: 'bootstrap4'
                    });
                    $("#tbody_div").html("");
                    tableRow_count = 0;
                    $("#count").html("(" + tableRow_count + "/8)");
                    $("#user_dataForm").show();
                    $("#activity_form").hide();
                } else {
                    toastsCall('bg-danger', 'Error', 'Invalid Information !');
                }

            },
            error: function (jqXhr) {
                HoldOn.close();
                toastsCall('bg-danger', 'Error', 'Internal Server Error!');
            }
        });
    }
    }
    )
}

function onChnageTarget() {
	$("#targetSatisfaction").val("");
	var targetText=$("#targetText").val().trim();
	if(targetText != ""){
		$("#targetAgreeDiv").show();
	}else{
		$("#targetAgreeDiv").hide()
	}
}

function onChangeTartgetMonitor() {
	$("#monitorFrequent").val("");
	var targetMonitor=$("#targetMonitor").val().trim();
	if(targetMonitor != ""){
		$("#monitorFrequentDiv").show();
	}else{
		$("#monitorFrequentDiv").hide()
	}
}
