@model Microsoft.Live.Web.Samples.AuthWithMSAccount.Models.JSClientModel
@{
    ViewBag.Title = "AjaxClient";
    var m = this.ViewData.Model;
}

<h2>AjaxClient</h2>

<div id="meName" class="Name"></div>
<div id="meImg"></div>
<div id="signin"></div>
<label>Current scope: </label><span id="currentScope"></span>

<script src="@m.JSPath"></script>
<script type="text/javascript">

    WL.Event.subscribe("auth.login", onLogin);
    WL.Event.subscribe("auth.logout", onLogout);

    WL.init({
        client_id: "@m.ClientId",
        redirect_uri: "@m.RedirectUri",
        response_type: "code",
        scope: "@m.Scope"
    });

    WL.ui({
        name: "signin",
        element: "signin"
    });


    var meImgInitialized = false;

    function setMe(clear) {

        var imgHolder = document.getElementById("meImg"),
            meNameHolder = document.getElementById("meName");
        if (clear) {
            imgHolder.innerHTML = "";
            meNameHolder.innerHTML = "";
            meImgInitialized = false;
            return;
        }

        if (meImgInitialized) return;

        var session = WL.getSession(),
            token = session != null ? session.access_token : null;

        if (token != null) {
            var url = "https://apis.live.net/v5.0/me/picture?access_token=" + escape(token);
            imgTagString = "<img src='" + url + "' />";
            imgHolder.innerHTML = imgTagString;

            WL.api({ path: "me", method: "get" }, function (response) {
                if (!response.error) {
                    document.getElementById("meName").innerHTML = response.first_name + " " + response.last_name;
                }
            });
            meImgInitialized = true;
        }
    }

    function onLogin(response) {
        document.getElementById("currentScope").innerText = response.session.scope.join(" ");
        setMe(false);
    }

    function onLogout(response) {
        document.getElementById("currentScope").innerText = "";
        setMe(true);
    }

    setMe(false);
</script>