@using System.Configuration;
@using SharpConnector.Constants;
@using SharpConnector.Models;
@model SharpConnector.Models.Login
@{
    Layout = "~/Views/Shared/_LoginLayout.cshtml";
}

@using (Html.BeginForm("Index", "Login", FormMethod.Post, new { @id = "login_sso_form", role = "form" }))
{
    <h2>Retrieving user information...</h2>
    <div style="display: none">
        <label class="full-label">Username</label>
        @Html.TextBoxFor(m => m.Username)
        <br><br>

        <label class="full-label">Password</label>
        @Html.PasswordFor(m => m.Password)

        <br><br>
        @Html.HiddenFor(m => m.AuthType, new { @Value = AuthType.SSO });
        <input type="submit" value="Login" class="right" disabled>
    </div>
}

<script>
    function GetLoginUser() {
        var _mfpApi = '@ConfigurationManager.AppSettings["MFP:apiUrl"]';
        var _mfpVer = '@ConfigurationManager.AppSettings["MFP:apiVersion"]';

        var reqStr = _mfpApi + 'mfpcommon/GetLoginUser/' + _mfpVer + '?res=jsonp&callback=errorSSOFunc';
            reqStr += '&vkey=' + '@HttpUtility.UrlEncode(HttpContext.Current.Session[MFP.APIKey].ToString())';

        jsonpRequest(reqStr, "ExecuteJobCallback");
    }

    // ------------------------------------------------------------------------------
    function ExecuteJobCallback(_retParam) {
        var loginName = _retParam["result"]["GetLoginUserResponse"]["login-name"];
        var email = _retParam["result"]["GetLoginUserResponse"]["email-address"];

        /*
        var displayName = _retParam["result"]["GetLoginUserResponse"]["display-name"];
        var domain = _retParam["result"]["GetLoginUserResponse"]["domain"];
        var employeeID = _retParam["result"]["GetLoginUserResponse"]["employee-id"];
        */

        var authUserID = !isEmpty(loginName) ? loginName : email;

        /* Send auth ID to server */
        var authUserIDInput = document.createElement('input');
        authUserIDInput.type = 'hidden';
        authUserIDInput.name = 'MFPAuthID';
        authUserIDInput.value = authUserID;
        $('#login_sso_form').appendChild(authUserIDInput);

        $('#login_sso_form').submit();
    }

    // ------------------------------------------------------------------------------
    function errorSSOFunc(param) {

        // remove  element
        document.getElementsByTagName("head")[0].removeChild(objScript);

        // Check response 
        if (param.error == null) {

            // Return to the original callback funciton.
            eval(returnFunc)(param);
        }
        else {
            // Show error message.
            alert('ERROR!\r\n' + param.error.code + '\r\n' + param.error.message);
            navigateTo('@Url.Action("Index", "Login")');
        }
    }
</script>