
//For store current mode ( dark or default, block or unlock )
var darkMode = false;
var blockMode = false;

var translateIsPresent = false;
var createDocument = false;
var { jsPDF } = window.jspdf; // pdf library
var doc = null; // contain pdf report
var version = ""; //contain version of application

//Variable that content chart for complexity password
var ctx = null;

//Variable that contain chart object
var myChart = null;

var lastMod = ""; // date of last backup

//Counters for account of password complexity
var weak = 0;
var good = 0;
var strong = 0;
var veryStrong = 0;

//States for complexity password
var WEAK_PASSWORD = "Weak";
var GOOD_PASSWORD = "Good";
var STRONG_PASSWORD = "Strong";
var VERYSTRONG_PASSWORD = "Very Strong";

//Total list name accounts
var weakAccounts = [];
var goodAccounts = [];
var strongAccounts = [];
var vStrongAccounts = [];

//COntest fro report content
var recipient = "";

//for store document uploaded
var documentUploaded = {};

$(document).ready(function () {

    //if you refresh, control if app is blocked or not
    setBlockStatus(null).then(function () {

        //Check if loggedbackToHome
        checkLogin().then(function (res) {

            if (!res) {
                window.location.href = "http://localhost:8080/html/notLogged.html";
            } else {

                let clickOpen = false;

                //INIT TUTORIAL
                //init guide
                tl.pg.init({
                    default_zindex: 9999, //show bar indicator on all elements
                    pg_caption: "PM Tutorial",
                    track_events_cb: function (currentAction) { //for track action
                        if (currentAction.indexOf("open") != -1) {
                            clickOpen = true;
                            $(".tlypageguide_back").hide();
                        } else {
                            clickOpen = false;
                        }
                    },
                    handle_doc_switch: function (currentElement, previousElement) { // for track what element is show

                        //For enable/disable buttons
                        if (currentElement == ".buttonCommands") {
                            $(".buttonCommands").trigger("click");
                        }

                        //For enable/disable buttons
                        if (currentElement == ".btnDocuments") {
                            $(".btnDocuments").trigger("click");
                        }

                        if (currentElement == ".aboutButton") {
                            $(".aboutButton").trigger("click");
                        }

                        if (currentElement == ".helpButton") {
                            $(".helpButton").trigger("click");
                        }

                        if (currentElement == ".translatorButton") {
                            $(".translatorButton").trigger("click");
                        }

                        if (currentElement == ".dashboardButton") {
                            $(".dashboardButton").trigger("click");
                        }

                        //for restore previous situation
                        if (previousElement == ".buttonCommands" && currentElement == "#btnDarkModeNavbar button") {
                            $(".buttonCommands").trigger("click");
                        }

                        if(previousElement ==  "#btnDarkModeNavbar button" && currentElement == "#btnBlockApplicationNavbar button")   {
                            $("#btnDarkModeNavbar button").trigger("click");
                        }

                        if (previousElement == ".btnDocument" && currentElement == "#buttonCommands button") {
                            $(".btnDocument").trigger("click");
                        }

                        if (currentElement == "#btnDarkModeNavbar button") {
                            $("#btnDarkModeNavbar button").trigger("click");
                        }

                        if (previousElement == "#btnDarkModeNavbar button" && currentElement == ".dashboardButton" && !clickOpen) {
                            $("#btnDarkModeNavbar button").trigger("click");
                        }
                    }
                });

                //when click on tab guide
                $("#tlyPageGuideToggles").click(function () {

                    //show guide on all elements
                    $("#tlyPageGuideMessages").css({ 'z-index': '9999' })
                })

                //Hide translator
                $("#google_translate_element").hide();

                //Set translator on off when html is loaded
                $(".toggleTranslation")[0].checked = false;
                translateIsPresent = $(".toggleTranslation")[0].checked;

                $(".container-fluid div").hide();

                //Show dashboard page always
                $("#dashboard").show();
                $("#dashboard div").show();

                //hide chart for complexity pasword
                $("#complexityPasswordContainer").hide();

                setTimeout(function () {
                    $(".darkMode").hide();
                }, 40);

                //Refresh backup report card
                refreshBackupReport();

                //Refresh backup warning for last modify
                refreshWarningLastBackup();

                //When click on command title
                $("#solTitle a").click(async function () {

                    //Hide all div container
                    $(".container-fluid div").hide();

                    //Show the element that have the same id of data-target name property of link
                    var target = "#" + $(this).data("target");
                    $(target).show();

                    //if click on dashboard, show all and refresh card reports, else show any div ( otherwise i see all cards )
                    //for load specific elements on page when click on page title
                    if (target == "#dashboard") {
                        $(target + " div").show();
                        refreshBackupReport();
                        refreshWarningLastBackup();
                    } else if (target === "#help") {
                        $(target + " div").show();
                        $(".spinner-border ").hide();
                    } else if (target === "#about") {

                        //initialise popover
                        $('[data-toggle="popover"]').popover();

                        //load application version
                        var version = await loadVersionApplication();

                        $(target + " div").show();
                        if (darkMode) {
                            $("#versionApplication").html("<label style='font-weight: bold; color: white'>Version:&nbsp;</label><label style='color: white'>" + version + "</label>")
                        } else {
                            $("#versionApplication").html("<label style='font-weight: bold; color: black'>Version:&nbsp;</label><label style='color: black'>" + version + "</label>")
                        }


                        //check if client is online
                        if (!window.navigator.onLine) {
                            $("#downoadLatestVersion").hide();
                        } else {
                            $("#downoadLatestVersion").show();
                        }
                    } else if (target === "#uploadDocument") {
                        $(target + " div").show();

                        //show and hide container controlling switch state leave last time
                        let obj = $(".toggleUploadDocument")[0];

                        if (obj.checked) {
                            $("#uploadDocumentContainer").hide();
                            $("#createDocumentContainer").show();
                            createDocument = true;

                            //delete previous content on input
                            $("#nameDocumentCreated").val("");
                            $("#contentDocument").val("");
                        } else {
                            $("#uploadDocumentContainer").show();
                            $("#createDocumentContainer").hide();
                            createDocument = false;
                        }
                    } else {
                        $(target + " div").show();
                    }
                });

                //When switch the translator button
                $(".toggleTranslation").change(function () {

                    if (translateIsPresent) {
                        $(".translateScript").remove();
                        $("#google_translate_element").hide();
                        translateIsPresent = false;
                        location.reload();
                    } else {
                        $("body").append("<script type='text/javascript' class='translateScript' src='//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'></script>");
                        $("#google_translate_element").show();
                        translateIsPresent = true;
                    }

                })

                // Toggle the side navigation
                $("#sidebarToggle").on("click", function (e) {
                    e.preventDefault();
                    $("body").toggleClass("sb-sidenav-toggled");
                });

                $(".backToHome").on("click", function () {

                    //Set login parameter equals false
                    setLogin(false).then(function () {

                        $("body").css("background-color", "black");
                        $("body").addClass("fadeOut");

                        setTimeout(function () {
                            window.location.href = "http://localhost:8080/index.html";
                        }, 2000);

                    });
                })

                //When modal is on page ( modal for ask master password used for ask reports )
                $('#masterPassModal').on('show.bs.modal', function (event) {
                    var button = $(event.relatedTarget) // Button/Link "View details" that triggered the modal
                    recipient = button.data('whatever') // Extract info from data-* attributes

                    //clear previous masterpassword
                    $('#masterPassToSend').val("");

                    var modal = $(this);

                    //Click on confirm button to obtain list accounts report
                    $("#btnConfirmMS").on("click", async function (event) {
                        event.stopImmediatePropagation();

                        //get masterPassword
                        var masterPassword = modal.find('#masterPassToSend').val()

                        //prepare data for server
                        var data = { masterPassword: masterPassword };

                        //If report required is for getList accounts
                        if (recipient == "getList") {

                            //Send request
                            var res = await getListAccounts(data);
                            if (res.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: res.error,
                                });
                            } else {
                                if (!res.error) {

                                    $("#totalAccounts").text(res.length);
                                    modal.modal('toggle'); //close modal
                                }
                            }
                        } else if (recipient == "getFavoriteList") {

                            //Send request
                            var res = await getListAccounts(data);

                            if (res.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: res.error,
                                });
                            } else {
                                res = res.filter(function (account) {
                                    if (account.isFavorite) {
                                        return account;
                                    }
                                });
                            }

                            if (!res.error) {

                                $("#totalFavoritesAccounts").text(res.length);
                                modal.modal('toggle'); //close modal
                            }
                        } else if (recipient == "getChartComplPassword") {

                            //Set initial value
                            weak = 0; good = 0; strong = 0; veryStrong = 0;

                            //Set initial value
                            weakAccounts = []; goodAccounts = []; strongAccounts = []; vStrongAccounts = [];

                            //Send request for obtain all data
                            var res = await getListAccounts(data);

                            //if masterpassword is not correct
                            if (res.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: res.error,
                                });
                            } else {

                                //if there are not accounts
                                if (res.length == 0) {
                                    iziToast.warning({
                                        title: 'Warning',
                                        message: "No accounts available.",
                                        displayMode: 'once'
                                    });
                                } else {
                                    res.forEach(function (account) {

                                        //Check Password complexity for all accounts
                                        checkPasswordComplexity(account)

                                    });

                                    //close modal
                                    modal.modal('toggle');

                                    //Create chart of complexity password
                                    createChart();
                                }
                            }
                        } else if (recipient == "getDocumentList") {

                            //Send request
                            var res = await getDocumentList(data);

                            //if masterpassword is not correct
                            if (res.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: res.error,
                                });
                            } else {
                                if (res.length > 0) {
                                    $("#totalDocuments").text(res.length);
                                } else {
                                    iziToast.warning({
                                        title: 'Warning',
                                        message: "No documents available.",
                                        displayMode: 'once'
                                    });
                                }
                                modal.modal('toggle'); //close modal
                            }
                        } else if (recipient == "unlockApplicationRequest") {

                            let res = await getListAccounts(data);

                            //if masterpassword is not correct
                            if (res.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: res.error,
                                    displayMode: 'once'
                                });
                            } else {

                                if(blockMode)   {
                                    blockMode = false;
                                } else  {
                                    blockMode = true;
                                }

                                modal.modal('toggle'); //close modal

                                //store status block on server and block/unlock application
                                await setBlockStatus(blockMode);
                            }
                        }
                    });
                });

                //When download button on backup card is clicked
                $(".downloadBackup").on("click", function () {
                    $.ajax({
                        type: 'GET',
                        contentType: 'application/json',
                        url: 'http://localhost:8080/downloadBackup',
                        success: function (data) {

                            //create a element and add data encrypted
                            var element = document.createElement('a');
                            element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
                            element.setAttribute('download', "backup.txt");

                            //add the element hide on body
                            element.style.display = 'none';
                            document.body.appendChild(element);

                            //click on the element for open download modal
                            element.click();

                            //remove hide element on body
                            document.body.removeChild(element);

                        }, error: function (xhr, status, error) {
                            //alert(error);
                        }
                    });
                });

                //Click on send btnSendEmail
                $(".btnSendEmail").click(() => {

                    $(".spinner-border ").show();
                    window.location.href = "mailto:passwordmanagerjs@protonmail.com?subject=&body=";

                    setTimeout(function () {
                        $(".spinner-border").hide();
                    }, 1500)
                });

                //Click on btnGeneratePass
                $(".btnGeneratePass").on("click", function () {

                    //get password
                    $.ajax({
                        type: 'GET',
                        contentType: 'application/json',
                        url: 'http://localhost:8080/generatePassword',
                        success: function (data) {
                            iziToast.success({
                                timeout: 20000,
                                overlay: true,
                                displayMode: 'once',
                                id: 'inputs',
                                zindex: 999,
                                title: 'Password generated',
                                message: '',
                                position: 'center',
                                drag: false,
                                inputs: [
                                    ['<input type="text" value=' + data.substring(data.indexOf(":") + 1, data.length) + '>', 'keyup', function (instance, toast, input, e) {
                                    }, true]
                                ]
                            });

                        }, error: function (xhr, status, error) {
                            //alert(error);
                        }
                    });
                });

                //Click on create button
                $(".btnCreateAccount").on("click", function () {

                    //Get all informations on page
                    var nameAccount = $("#inputNameAccount").val();
                    var username = $("#inputUsernameAccount").val();
                    var password = $("#inputPasswordAccount").val();
                    var isFavorite = $('#inputFavoriteAccount:checked').length > 0

                    if (nameAccount != "" && username != "" && password != "") {

                        //Get masterpassword val
                        var masterPassword = $("#inputMasterPasswordCreate").val();

                        var data = {};
                        data.name = nameAccount;
                        data.username = username;
                        data.password = password;
                        data.isFavorite = isFavorite;

                        //get password
                        $.ajax({
                            type: 'POST',
                            data: JSON.stringify({ account: data, masterPassword: masterPassword }),
                            contentType: 'application/json',
                            url: 'http://localhost:8080/createAccount',
                            success: function (data) {

                                //if masterpassword is not correct
                                if (data.error) {
                                    iziToast.warning({
                                        title: 'Warning',
                                        message: data.error,
                                    });
                                } else {
                                    iziToast.success({
                                        title: 'Success',
                                        message: data,
                                    });
                                }
                            }, error: function (xhr, status, error) {
                                iziToast.error({
                                    title: 'Error',
                                    message: error,
                                });
                            }
                        });
                    } else {
                        iziToast.warning({
                            title: 'Warning',
                            message: 'Compile all fields!'
                        });
                    }
                });

                //Click get button
                $(".btnGetAccount").on("click", function () {

                    //Get name
                    var nameAccount = $("#inputNameAccountGet").val();

                    //Get masterpassword val
                    var masterPassword = $("#inputMasterPasswordGet").val();
                    //get password
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify({ name: nameAccount, masterPassword: masterPassword }),
                        contentType: 'application/json',
                        url: 'http://localhost:8080/getAccount',
                        success: function (data) {

                            if (!data.isFavorite) {
                                data.isFavorite = false;
                            }

                            if (data.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error,
                                });
                            } else {
                                iziToast.success({
                                    timeout: 20000,
                                    overlay: true,
                                    displayMode: 'once',
                                    id: 'inputs',
                                    zindex: 9990,
                                    title: 'Account matched',
                                    message: '',
                                    position: 'center',
                                    drag: false,
                                    inputs: [
                                        ['<label>&nbsp;Name:&nbsp;</label><input type="text" value=' + data.name + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],

                                        ['<label>&nbsp;Username:&nbsp;</label><input type="text" value=' + data.username + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                        ['<label>&nbsp;Password:&nbsp;</label><input type="text" value=' + data.password + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                        ['<label>&nbsp;Favorite:&nbsp;</label><input type="text" value=' + data.isFavorite + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                    ]
                                });
                            }
                        }, error: function (xhr, status, error) {
                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //Click modify button
                $(".btnModifyAccount").on("click", function () {

                    //Get all informations on page
                    var nameAccount = $("#inputNameAccountModify").val();
                    var username = $("#inputUsernameAccountModify").val();
                    var password = $("#inputPasswordAccountModify").val();
                    var isFavorite = $('#inputFavoriteModAccount:checked').length > 0

                    //Get masterpassword val
                    var masterPassword = $("#inputMasterPasswordModify").val();

                    var data = {};
                    data.name = nameAccount;
                    data.username = username;
                    data.password = password;
                    data.isFavorite = isFavorite;

                    //get password
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify({ account: data, masterPassword: masterPassword }),
                        contentType: 'application/json',
                        url: 'http://localhost:8080/modifyAccount',
                        success: function (data) {

                            if (data.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error,
                                });
                            } else {
                                iziToast.success({
                                    timeout: 20000,
                                    overlay: true,
                                    displayMode: 'once',
                                    id: 'inputs',
                                    zindex: 9990,
                                    title: 'Account changed',
                                    message: '',
                                    position: 'center',
                                    drag: false,
                                    inputs: [
                                        ['<label>&nbsp;Name: </label><input type="text" value=' + data.name + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],

                                        ['<label>&nbsp;Username: </label><input type="text" value=' + data.username + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                        ['<label>&nbsp;Password: </label><input type="text" value=' + data.password + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                        ['<label>&nbsp;Favorite: </label><input type="text" value=' + data.isFavorite + '>', 'keyup', function (instance, toast, input, e) {
                                        }, true],
                                    ]
                                });
                            }
                        }, error: function (xhr, status, error) {
                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //Click on btngetList
                $(".btngetList").on("click", async function () {

                    await setListAccountsOnPage(false);
                });

                //Click on btngetList
                $(".btngetListFavorites").on("click", async function () {

                    await setListAccountsOnPage(true);

                    //Show PDF button
                    $(".downloadPDFFavorites").show();

                });

                //Click delete button
                $(".btnDeleteAccount").on("click", function () {

                    //Get name
                    var nameAccount = $("#inputNameAccountDelete").val();

                    //Get masterpassword val
                    var masterPassword = $("#inputMasterPasswordDelete").val();

                    //get password
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify({ name: nameAccount, masterPassword: masterPassword }),
                        contentType: 'application/json',
                        url: 'http://localhost:8080/deleteAccount',
                        success: function (data) {

                            if (data.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error
                                });
                            } else {
                                iziToast.success({
                                    title: 'Success',
                                    message: data
                                });
                            }
                        }, error: function (xhr, status, error) {
                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //Click delete all button
                $(".btnDeleteAll").on("click", function () {

                    //Get masterpassword val
                    var masterPassword = $("#inputMasterPasswordDeleteAll").val();

                    //get password
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify({ masterPassword: masterPassword }),
                        contentType: 'application/json',
                        url: 'http://localhost:8080/deleteAll',
                        success: function (data) {

                            if (data.error) {
                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error
                                });
                            } else {
                                iziToast.success({
                                    title: 'Success',
                                    message: data
                                });
                            }
                        }, error: function (xhr, status, error) {

                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //Click backup button
                $(".btnBackup").on("click", function () {

                    //Get path
                    var path = $("#inputBackup").val();

                    //get password
                    $.ajax({
                        type: 'GET',
                        contentType: 'application/json',
                        url: 'http://localhost:8080/backup',
                        success: function (data) {

                            if (data.error) {

                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error
                                });
                            } else {

                                iziToast.success({
                                    title: 'Success',
                                    message: data
                                });
                            }
                        }, error: function (xhr, status, error) {

                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //When click on popover of warningBackup
                $(".oldBackup").on("click", function()  {
                    //initialise popover
                    $(this).attr("data-content", "Your last backup has been created on: " + lastMod);
                    $('[data-toggle="popoverBackup"]').popover();
                    
                })

                //Click restore button
                $(".btnRestore").on("click", function () {

                    //get password
                    $.ajax({
                        type: 'GET',
                        contentType: 'application/json',
                        url: 'http://localhost:8080/restore',
                        success: function (data) {

                            if (data.error) {

                                iziToast.warning({
                                    title: 'Warning',
                                    message: data.error
                                });
                            } else {

                                iziToast.success({
                                    title: 'Success',
                                    message: data
                                });
                            }
                        }, error: function (xhr, status, error) {

                            iziToast.error({
                                title: 'Error',
                                message: error
                            });
                        }
                    });
                });

                //Clicck dark mode button
                $("#btnDarkMode").on("click", function () {

                    //if using normal mode
                    if (!darkMode) {
                        darkMode = true;
                        $(".darkMode").show(); //show moon icon for dark mode
                        $(".defaultMode").hide(); // hide moon icon for default mode
                        $("#layoutSidenav_content").css("background-color", "#2d2d2d"); // set dark color on content
                        $("#layoutSidenav_content").find("label:not(.switch-off):not(#totalDocuments):not(#totalFavoritesAccounts):not(#totalAccounts)").css("color", "white"); // set white color for all labels
                        $("#layoutSidenav_content").find("#dataTable tr").css("color", "white"); // set white color for all table rows

                        //update title of document list decrypted
                        $(".listDocsDecrypted p").css({ "color": "white" });

                    } else {
                        darkMode = false;
                        $(".darkMode").hide();//hide moon icon for dark mode
                        $(".defaultMode").show();// show moon icon for default mode
                        $("#layoutSidenav_content").css("background-color", "white");// set white color on content
                        $("#layoutSidenav_content").find("label:not(#totalDocuments):not(#totalFavoritesAccounts):not(#totalAccounts)").css("color", "black");// set black color for all labels
                        $("#layoutSidenav_content").find("#dataTable tr").css("color", "black");// set black color for all table rows

                        //update title of document list decrypted
                        $(".listDocsDecrypted p").css({ "color": "black" });
                    }
                });

                //When click on "DownloadPDF"on getlist command
                $(".downloadPDFGetList").on("click", function () {
                    createPdfReport();
                })

                //When click on "DownloadPDF"on chart of password complexity
                $(".downloadPDFPassComplexity").on("click", function () {
                    createPdfReport();
                })

                //When click on "DownloadPDF"on favorites command
                $(".downloadPDFFavorites").on("click", function () {
                    createPdfReport();
                })

                //When switch the UploadDocument button
                $(".toggleUploadDocument").change(function (obj) {

                    //if "createdocument" is cheched, show and hide containers
                    if (obj.target.checked) {
                        $("#uploadDocumentContainer").hide();
                        $("#createDocumentContainer").show();
                        createDocument = true;

                        //delete previous content on input
                        $("#nameDocumentCreated").val("");
                        $("#contentDocument").val("");
                    } else {
                        $("#uploadDocumentContainer").show();
                        $("#createDocumentContainer").hide();
                        createDocument = false;
                    }
                })

                // When click on upload button on upload document command
                $(".btnUploadDocument").on("click", async function () {

                    //Get master password
                    var masterPassword = $("#inputMasterPasswordUploadDoc").val();

                    //if you upload file 
                    if (!createDocument) {

                        //if file has been selected and masterpassword has been inserted
                        if ($("#btnUploadDocument").val() !== "" && masterPassword !== "") {

                            await encryptDocument(masterPassword);
                        }
                    } else {
                        let valTextArea = $("#contentDocument").val();

                        //if file has been created and masterpassword has been inserted
                        if (valTextArea !== "" && masterPassword !== "") {

                            //Save document name
                            documentUploaded.name = $("#nameDocumentCreated").val() + ".txt";

                            //save document data
                            documentUploaded.data = valTextArea;

                            await encryptDocument(masterPassword);
                        }
                    }
                })

                //When click on confirm button on getListDocument command
                $(".btnListDocument").on("click", async function () {
                    var masterPassword = $("#inputMasterPasswordListDoc").val();

                    if (masterPassword !== "") {
                        
                        //Get and create document list
                        await getCreateDocumentList(masterPassword);

                        //after few time, set click event on icons ! Otherwise not await and these icons will not yet on page
                        setTimeout(function () {

                            //When click on trash icon of document
                            $(".deleteDocument").on("click", async function () {

                                var nameFile = $(this).prev().html();
                                await deleteDocument(this, nameFile);
                            });

                            //When click on trash icon of document
                            $(".openDocument").on("click", async function () {

                                var nameFile = $(this).prev().prev().html();
                                var documentContent = await getDocument(nameFile, masterPassword);

                                $("#contentDocumentModal").modal("toggle");
                                $("textarea#contentDocumentPreview").val(documentContent.data);
                                $("textarea#contentDocumentPreview").prop('disabled', true);
                            })
                        }, 50)
                    }
                });
            }
        });
    });
});


/**
 * Get list of accounts
 * @param {*} data -> object that contain masterpassword
 */
function getListAccounts(data) {
    return new Promise((resolve, reject) => {

        //get list accounts
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            url: 'http://localhost:8080/getList',
            success: function (data) {
                resolve(data);
            }, error: function (xhr, status, error) {
                iziToast.error({
                    title: 'Warning',
                    message: error,
                });
            }
        })
    })
};

/**
 * Insert data on table
 * @param {*} isFavorite -> boolean to get list favorites accounts or not
 */
async function setListAccountsOnPage(isFavorite) {

    //Get masterpassword val
    var masterPassword = "";

    if (isFavorite) {
        masterPassword = $("#inputMasterPasswordListFav").val();
        $("#tableListAccountsFav").html("");

    } else {
        masterPassword = $("#inputMasterPasswordList").val();
        $("#tableListAccounts").html("");
    }

    //if masterpassword is not empty
    if (masterPassword !== "") {

        var data = {};
        data.masterPassword = masterPassword;

        //get list accounts
        var res = await getListAccounts(data);

        //if masterpassword is not correct
        if (res.error) {
            iziToast.warning({
                title: 'Warning',
                message: res.error,
            });

            if (isFavorite) {
                //clean table
                $("#tableListAccountsFav").html("");

            } else {

                //clean table
                $("#tableListAccounts").html("");

            }
        } else {
            //if command is for get list favorites accounts
            if (isFavorite) {
                //filter for favorite account
                res = res.filter(function (account) {
                    if (account.isFavorite) {
                        return account;
                    }
                });
            }

            //if accounts list is empty
            if (res.length == 0) {
                iziToast.warning({
                    title: 'Warning',
                    message: "No accounts available",
                });
            } else {

                //create new pdf object
                doc = new jsPDF();
                var line = 0;

                //set title
                line += 10;
                doc.setFontSize(22);
                doc.setTextColor(0, 0, 255)
                var title = "";
                if (isFavorite) {
                    title = "PasswordManager - List of your favorites accounts";
                } else {
                    title = "PasswordManager - List of your accounts";
                }

                doc.text(20, line, title)
                doc.setFontSize(16); // set font for accounts list

                //show accounts
                res.forEach(function (element) {
                    if (isFavorite) {
                        if (!darkMode) {
                            $("#tableListAccountsFav").append("<tr><td>" + element.name + "</td><td>" + element.username + "</td><td>" + element.password + "</td><td>" + element.isFavorite + "</td></tr>")
                        } else {

                            $("#tableListAccountsFav").append("<tr style='color: white'><td>" + element.name + "</td><td>" + element.username + "</td><td>" + element.password + "</td><td>" + element.isFavorite + "</td></tr>")
                        }
                    } else {
                        if (!darkMode) {
                            $("#tableListAccounts").append("<tr><td>" + element.name + "</td><td>" + element.username + "</td><td>" + element.password + "</td></tr>")
                        } else {
                            $("#tableListAccounts").append("<tr style='color:white'><td>" + element.name + "</td><td>" + element.username + "</td><td>" + element.password + "</td></tr>")
                        }
                    }
                    
                    //New line for new account information
                    line += 10;
                    line = controlPDFLine(line);
                    doc.setTextColor(0,0,0)
                    doc.text(20, line, "Username: " + element.name + " - Password: " + element.password);
                });
            }

            //Show PDF button
            $(".downloadPDFGetList").show();
        }
    }
}

/**
 * Sve PDF document created on application
 */
function createPdfReport() {

    if (doc) {
        doc.save("Accounts.pdf"); // will save the file in the current working directory
    }

}
/**
 * Refresh backup report card
 */
function refreshBackupReport() {

    //get list accounts
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'http://localhost:8080/checkBackup',
        success: function (data) {
            if (data.error) {
                $("#cardBackupWarning").show();
                $("#cardBackupSuccess").hide();
            } else {
                $("#cardBackupWarning").hide();
                $("#cardBackupSuccess").show();
            }
        }, error: function (xhr, status, error) {
            //alert(error);
        }
    })
}

function googleTranslateElementInit() {
    new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
}

/**
 * Control password complexity to account
 * @param account -> account object to control
 */
function checkPasswordComplexity(account)  {
    var result = "";

    var password = account.password;

    //TextBox left blank.
    if (password.length == 0) {
        return result;
    }

    //Regular Expressions.
    var regex = new Array();
    regex.push("[A-Z]"); //Uppercase Alphabet.
    regex.push("[a-z]"); //Lowercase Alphabet.
    regex.push("[0-9]"); //Digit.
    regex.push("[$@$!%*#?&]"); //Special Character.

    var passed = 0;

    //Validate for each Regular Expression.
    for (var i = 0; i < regex.length; i++) {
        if (new RegExp(regex[i]).test(password)) {
            passed++;
        }
    }

    //Validate for length of Password.
    if (passed > 2 && password.length > 8) {
        passed++;
    }

    //Display status.
    var color = "";
    var strength = "";
    switch (passed) {
        case 0:
        case 1:
            result = WEAK_PASSWORD;
            color = "red";
            weak++;
            weakAccounts.push(account.name);
            break;
        case 2:
            result = GOOD_PASSWORD;
            color = "darkorange";
            good++;
            goodAccounts.push(account.name);
            break;
        case 3:
        case 4:
            result = STRONG_PASSWORD;
            color = "green";
            strong++;
            strongAccounts.push(account.name);
            break;
        case 5:
            result = VERYSTRONG_PASSWORD;
            color = "darkgreen";
            veryStrong++;
            vStrongAccounts.push(account.name);
            break;
    }
    return result;
}

/**
 * Create chart for show complexity passwords
 */
function createChart() {

    //get chart on html page
    ctx = document.getElementById('myChart').getContext('2d');

    //If exist
    if(myChart) {
        myChart.destroy(); // destroy for not to duplicate chart
    }

    //create chart
    myChart = new Chart(ctx, {
        type: "doughnut",
        data: {
            labels: [WEAK_PASSWORD, GOOD_PASSWORD, STRONG_PASSWORD, VERYSTRONG_PASSWORD], // label on top of the chart
            datasets: [{
                data: [weak, good, strong, veryStrong], //data to show on chart
                backgroundColor: [
                    'rgba(255, 0, 0, 0.2)',
                    'rgba(51, 204, 255, 0.2)',
                    'rgba(0, 102, 255, 0.2)',
                    'rgba(0, 255, 0, 0.2)'
                ],
                borderColor: [
                    'rgba(255, 99, 132, 1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true, // for set dimensions on the device that you use - default true
            legend: {
                position: 'top',
            },
            title: {
                display: true,
                text: 'Password complexity'
            },
            animation: {
                animateScale: true, //animation when mouse is hover
                animateRotate: true
            },
            onClick: function (ev, data) { // when click on chart section
                ev.stopImmediatePropagation();

                //if you clicked on chart
                if (data.length != 0) {

                    //create new pdf object
                    doc = new jsPDF();
                    var line = 0;

                    //set title
                    line += 10;
                    doc.setFontSize(22);
                    doc.setTextColor(0, 0, 255)
                    var title = "PasswordManager - List of your accounts";

                    doc.text(20, line, title)
                    doc.setFontSize(16); // set font for accounts list
                    doc.setTextColor(0, 0, 0)

                    //Delete previous accounts on list
                    $("#complexityPasswordModal .modal-body").find("#listAccounts").html("");

                    //Show modal for chart
                    $("#complexityPasswordModal").modal("toggle");

                    //Show PDF button
                    $(".downloadPDFPassComplexity").show();

                    //If you click on weak accounts credentials
                    if (data[0]['_model'].label == WEAK_PASSWORD) {

                        weakAccounts.forEach(function (nameAccount) {
                            $("#complexityPasswordModal .modal-body").find("#listAccounts").append("<p>" + nameAccount + "</p>")

                            //New line for new account information
                            line += 10;
                            line = controlPDFLine(line);
                            doc.text(20, line, "Username: " + nameAccount);
                        })
                    }
                    //If you click on good accounts credentials
                    if (data[0]['_model'].label == GOOD_PASSWORD) {

                        goodAccounts.forEach(function (nameAccount) {
                            $("#complexityPasswordModal .modal-body").find("#listAccounts").append("<p>" + nameAccount + "</p>")

                            //New line for new account information
                            line += 10;
                            line = controlPDFLine(line);
                            doc.text(20, line, "Username: " + nameAccount);
                        })
                    }
                    //If you click on strong accounts credentials
                    if (data[0]['_model'].label == STRONG_PASSWORD) {

                        strongAccounts.forEach(function (nameAccount) {
                            $("#complexityPasswordModal .modal-body").find("#listAccounts").append("<p>" + nameAccount + "</p>")

                            //New line for new account information
                            line += 10;
                            line = controlPDFLine(line);
                            doc.text(20, line, "Username: " + nameAccount);
                        })
                    }
                    //If you click on very strong accounts credentials
                    if (data[0]['_model'].label == VERYSTRONG_PASSWORD) {

                        vStrongAccounts.forEach(function (nameAccount) {
                            $("#complexityPasswordModal .modal-body").find("#listAccounts").append("<p>" + nameAccount + "</p>")

                            //New line for new account information
                            line += 10;
                            line = controlPDFLine(line);
                            doc.text(20, line, "Username: " + nameAccount);

                        })
                    }
                }
            }
        }
    });
}

/**
 * Check complexity password when digit on field "password" when create new account
 * @param password -> password typeof string
 */
function checkPassword(password) {

    // if password exist
    if (password !== "") {

        //Set initial value
        weakAccounts = []; goodAccounts = []; strongAccounts = []; vStrongAccounts = [];

        //Set initial value
        weak = 0; good = 0; strong = 0; veryStrong = 0;

        //Check complexity password
        let result = checkPasswordComplexity({ name: "", password: password });

        //color label depending of complexity
        if (result == WEAK_PASSWORD) {
            $("#strengthPass").css("color", "red");
        } else if (result == GOOD_PASSWORD) {
            $("#strengthPass").css("color", "orange");
        } else if (result == STRONG_PASSWORD) {
            $("#strengthPass").css("color", "blue");
        } else if (result == VERYSTRONG_PASSWORD) {
            $("#strengthPass").css("color", "green");
        }

        //Set result
        $("#strengthPass").text("Complexity level: " + result);
    } else {

        //if password not exist, set empty result
        $("#strengthPass").text("");
    }
}

/**
 * Read document uploaded from "upload document" command. 
 * Will be called from onchange event on html file
 * @param {*} input -> File object
 */
function readDocument(input) {
    var file = input.files[0];

    //Save document name
    documentUploaded.name = input.files[0].name;

    let reader = new FileReader();

    //Read file
    reader.readAsText(file);

    //When file is readed
    reader.onload = async function () {

        //save document data
        documentUploaded.data = reader.result;

        //Set title file on label input file
        $(".labelUploadDoc").html(documentUploaded.name);

        iziToast.success({
            title: 'Success',
            message: "Document uploaded",
        });
    };

    reader.onerror = function () {
        iziToast.warning({
            title: 'Warning',
            message: reader.error,
        });
    };

} 

/**
 * Call server for encrypt document
 */
async function encryptDocument(masterPassword)  {
    return new Promise((resolve, reject) => {

        $.ajax({
            type: 'POST',
            data: JSON.stringify({ dataFile: documentUploaded.data, name: documentUploaded.name, masterPassword: masterPassword}),
            contentType: 'application/json',
            url: 'http://localhost:8080/encryptDocument',
            success: function (res) {

                if (res.error) {
                    iziToast.warning({
                        title: 'Warning',
                        message: res.error,
                    });
                } else  {
                    iziToast.success({
                        title: 'Success',
                        message: "Document encrypted",
                    });
                }

                resolve();
            }
        });
    })
}

/**
 * Obtain document encrypted list and create list on "list document" page
 * @param {*} masterPassword -> masterPassword
 */
async function getCreateDocumentList(masterPassword)  {
    return new Promise((resolve, reject) => {

        $.ajax({
            type: 'POST',
            data: JSON.stringify({ masterPassword: masterPassword}),
            contentType: 'application/json',
            url: 'http://localhost:8080/getDocumentList',
            success: function (res) {

                if (res.error) {
                    iziToast.warning({
                        title: 'Warning',
                        message: res.error,
                    });
                } else {

                    if (res.length == 0) {
                        iziToast.warning({
                            title: 'Warning',
                            message: "No document found",
                        });
                    } else {
                        iziToast.success({
                            title: 'Success',
                            message: "Documents decrypted",
                        });

                        //Delete previous content
                        $(".listDocsDecrypted").html("");

                        //update title of document list decrypted
                        if(darkMode)    {
                            $(".listDocsDecrypted").append("<p style='color: white'>List of docs: </p>");
                        } else  {
                            $(".listDocsDecrypted").append("<p style='color: black'>List of docs: </p>");
                        }

                        //for all docs
                        res.forEach(function (file) {

                            //Create file
                            createFile(file);
                        })
                    }
                }

                resolve();
            }
        });
    })
}


/**
 * Obtain document encrypted 
 * @param {*} nameDocument -> name of document
 * @param {*} masterPassword -> masterPassword
 */
async function getDocument(nameDocument, masterPassword)  {
    return new Promise((resolve, reject) => {

        $.ajax({
            type: 'POST',
            data: JSON.stringify({ nameDocument: nameDocument, masterPassword: masterPassword}),
            contentType: 'application/json',
            url: 'http://localhost:8080/getDocumentList',
            success: function (res) {

                if (res.error) {
                    iziToast.warning({
                        title: 'Warning',
                        message: res.error,
                    });
                } else {

                    if (res.length == 0) {
                        iziToast.warning({
                            title: 'Warning',
                            message: "No document found",
                        });
                    } else {
                        resolve(res[0]);
                    }
                }
            }
        })
    })
}

/**
 * Obtain document encrypted list
 * @param {*} data -> object that contain masterPassword
 */
async function getDocumentList(data)    {
    return new Promise((resolve, reject) => {

        $.ajax({
            type: 'POST',
            data: JSON.stringify({ masterPassword: data.masterPassword}),
            contentType: 'application/json',
            url: 'http://localhost:8080/getDocumentList',
            success: function (res) {

                resolve(res);
            }
        });
    })
}

/**
 * For delete existing document
 * @param {*} trashObj -> jquery object of trash icon
 * @param {*} name -> name file that will be deleted
 */
async function deleteDocument(trashObj, name) {
    return new Promise((resolve, reject) => {

        $.ajax({
            type: 'POST',
            data: JSON.stringify({ nameFile: name }),
            contentType: 'application/json',
            url: 'http://localhost:8080/deleteDocument',
            success: function (res) {

                if (res.error) {
                    iziToast.warning({
                        title: 'Warning',
                        message: res.error,
                    });
                } else {

                    iziToast.success({
                        title: 'Success',
                        message: "Documents deleted",
                    });

                    //Delete document on body
                    $(trashObj).siblings("a").each(function(index, rowDocument)   {
                        if($(rowDocument).attr("download") == name) {
                            $(rowDocument).remove();
                            $(trashObj).next(".openDocument").remove();
                            $(trashObj).remove();
                        }
                    })
                }

                resolve();
            }
        });
    })
}

/**
 * Create and append file on page
 * @param {*} file -> file object: {name, data:String}
 */
function createFile(file) {
    var atag = document.createElement("a");
    atag.className = "documentName";
    var fileToDownload = new Blob([file.data], {type: "text/plain"});
    atag.href = URL.createObjectURL(fileToDownload);
    atag.download = file.name;
    atag.text = file.name;

    $(".listDocsDecrypted").append(atag)
    .append("&nbsp; &nbsp; <i class='fa fa-trash deleteDocument' aria-hidden='true' style='color:red;'></i>")
    .append("&nbsp; &nbsp; <i class='fas fa-file-alt openDocument' aria-hidden='true' style='color:blue;'></i>")
    .append("<br>");
}

/**
 * Control if page is full
 * @param {*} line -> current line
 */
function controlPDFLine(line) {

    //If page is end
    if (line == 290) {
        doc.addPage(); // create another page
        line = 10; // start on first line
    }
   return line;
}

/**
 * Check if login has beed do with QRCode
 */
async function checkLogin() {
    return new Promise((resolve, reject) => {

        //check if is logged
        $.ajax({
            type: 'GET',
            contentType: 'application/json',
            url: 'http://localhost:8080/checkLogin',
            success: function (data) {

                if (data) {
                    resolve(true);
                } else  {
                    resolve(false);
                }
            }
        });
    })
}

//Set login status
async function setLogin(state) {
    return new Promise((resolve, reject) => {

        //check if is logged
        $.ajax({
            type: 'POST',
            data: JSON.stringify({ state: state }),
            contentType: 'application/json',
            url: 'http://localhost:8080/setLogin',
            success: function (data) {

              resolve();
            }
        });
    })
}

/**
 * Check version of application
 */
async function loadVersionApplication() {
    return new Promise((resolve, reject) => {
        if (version === "") {

            //check version
            $.ajax({
                type: 'GET',
                contentType: 'application/json',
                url: 'http://localhost:8080/checkVersion',
                success: function (data) {

                    version = data;
                    resolve(version);
                }
            });

        } else {
            resolve(version);
        }
    })
}

/**
 * Enable or disable block mode
 */
async function controlBlockApplication()  {
    return new Promise((resolve, reject) => {
        //check block status
        $.ajax({
            type: 'GET',
            contentType: 'application/json',
            url: 'http://localhost:8080/blockStatus',
            success: function (statusBlock) {
                blockMode = statusBlock;

                //if is not blocked
                if (!blockMode) {
                    
                    $(".lockApp").show();
                    $(".unlockApp").hide();

                    $(".blockContainer").hide();

                    iziToast.success({
                        title: 'Success',
                        message: "Application unlocked",
                    });
                    resolve();
                } else {
                    $(".unlockApp").show();
                    $(".lockApp").hide();

                    $(".blockContainer").show();

                    iziToast.success({
                        title: 'Success',
                        message: "Application blocked",
                    });
                    resolve();
                }

                
            }
        });

    })
}

/**
 * Set block application status
 * @param blockStatus -> new status: true or false
 */
async function setBlockStatus(blockStatus) {
    return new Promise(async (resolve, reject) => {

        if (blockStatus !== null) {
            //check block status
            $.ajax({
                type: 'POST',
                data: JSON.stringify({ state: blockStatus }),
                contentType: 'application/json',
                url: 'http://localhost:8080/setBlockStatus',
                success: function () {

                    //block/unlock application
                    controlBlockApplication().then(function () {



                        resolve();
                    });
                }
            });
        } else {

            //block/unlock application
            await controlBlockApplication();

            resolve();
        }

    })
}


function refreshWarningLastBackup() {
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'http://localhost:8080/getInfoLastBackup',
        success: function (data) {
            lastMod = data.lastMod.substring(0, data.lastMod.indexOf(" "));
            lastMod = convertDate(lastMod);

            var now = data.today.substring(0, data.today.indexOf(" "));
            now = convertDate(now);

            if(lastMod !== now) {
                $(".oldBackup").show();
            } else  {
                $(".oldBackup").hide();
            }

        }, error: function (xhr, status, error) {
            //alert(error);
        }
    });
}

/**
 * COnvert date YYYY-MM-DD to DD/MM/YYYY
 * @param {*} data -> string date YYYY-MM-DD
 */
function convertDate(data) {
    var day = data.substring(data.lastIndexOf("-") + 1, data.length)
    var month = data.substring(data.indexOf("-") + 1, data.indexOf("-") + 3);
    var year = data.substring(0, data.indexOf("-"))
    data = day + "/" + month + "/" + year;
    return data;
}