$(document).ready(function(){
    var usernamefield=$("#inputEmail"),
        passwordfield=$('#inputPassword'),
        loginbutton=$("#loginbutton"),
        errordiv=$("#errordiv"),
        companylist=$("#company"),
        companies={"jozibeck":"jozibeck_rentmanager"},
        rs="<option value=''>&lt;Choose One&gt;</option>"
    
    // add database and company details to the companies drop down
    for (let [key, value] of Object.entries(companies)) {
        rs+=`<option value='${value}'>${key}</option>`;
    }

    companylist.html(rs)

    loginbutton.on("click",function(){
        //console.log("Logon button clicked")
        var username=usernamefield.val(),
            password=passwordfield.val(),
            company=companylist.val()
            errors=""
        if(username==""){
            errors="Please provide username"
            usernamefield.focus()
        }else if(password==""){
            errors="Please provide password"
            passwordfield.focus()
        }else if(company==""){
            errors="Please select company."
            companylist.focus()
        }
        //console.log(errors)
        if(errors==""){           
            $.post(
                "controllers/useroperations.php",
                {
                    loginuser:true,
                    username:username,
                    password:password,
                    database:company
                },
                function(data){
                    data=$.trim(data)
                    //console.log(data)
                    if (data=="success"){
                        window.location.href="views/smsmailer.php"
                    }else if (data=="change password"){
                        window.location.href="views/changepassword.php"
                    }else if(data=="account inactive"){
                        errors="Account disabled."
                        errordiv.html(showAlert("info",errors))
                    }else if(data=="invalid credentials"){
                        errors="Invalid credentials."
                        errordiv.html(showAlert("danger",errors))
                    }
                    if(errors!=""){
                        errordiv.html(showAlert("danger",errors))
                    }
                }
            )
        }else{
            errordiv.html(showAlert("info",errors))
        }
    })

    usernamefield.on("input",function(){
        errordiv.html("")
    })

    passwordfield.on("input",function(){
        errordiv.html("")
    })
})