﻿function TaloyhtioLoginSucceed(url) {
    if (typeof (url) == "undefined" || url == null || url == '') {
        return;
    }
    jQuery("#taloyhtioLoginFailed").html("");
    jQuery("#taloyhtioLoginSucceed").html("Kirjaudutaan...");
    window.location = url;
}

function TaloyhtioLoginFailed() {
    jQuery("#taloyhtioLoginFailed").html("Kirjautuminen epäonnistui");
    jQuery("#taloyhtioLoginSucceed").html("");
}

function TaloyhtioLogin(uid, pwd, targetHost, redirectUrl, loginFailedHandler) {
    try {
        if (typeof (targetHost) == "undefined" || targetHost == null || targetHost == '') {
            return;
        }
        var targetUrl = targetHost + "/_layouts/Taloyhtio/credentials/Credentials.asmx/GetRedirectUrlIfCredentialsAreValid";
        jQuery.ajax({
            url: targetUrl,
            data: { userName: "'" + uid + "'", password: "'" + pwd + "'", redirectUrlAfterLogin: "'" + redirectUrl + "'" },
            dataType: "jsonp",
            success: function(msg) {
                if (typeof (msg) == "undefined" || msg == null) {
                    return;
                }
                var result = msg.d;
                if (typeof (result) == "undefined" || result == null) {
                    if (loginFailedHandler != null) {
                        loginFailedHandler();
                    }
                    else {
                        TaloyhtioLoginFailed();
                    }
                    return;
                }

                TaloyhtioLoginSucceed(result);
            }
        });
    }
    catch(er) {
    }
}
