(function(context,$) {

    "use strict";

    context.JK = context.JK || {};

    context.JK.joinMusicSession = function(session_id, app) {
        var logger = context.JK.logger;
        var server = context.JK.JamServer;
        var client = context.jamClient;

        if (!server.signedIn)
        {
            logger.log("Can't join a session because the client is not connected.");
            return;
        }

        logger.log("Joining session: " + session_id);


        // FIXME. Setting tracks for join session. Only looking at profile
        // for now. Needs to check jamClient instruments and if set, use those
        // as first preference.
        var track = { instrument_id: "electric guitar", sound: "stereo" };
        if (context.JK.userMe.instruments.length) {
            track = {
                instrument_id: context.JK.userMe.instruments[0].instrument_id,
                sound: "stereo"
            };
        }

        var data = {
            client_id: server.clientID,
            ip_address: server.publicIP,
            as_musician: true,
            tracks: [ track ]
        };
        var url = "/api/sessions/" + session_id + "/participants";
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            url: url,
            data: JSON.stringify(data),
            processData:false,
            success: function(response) {
                context.JK.Sessions.JoinSession(session_id);
                if (client !== undefined) {
                    client.JoinSession({ sessionID: session_id });
                }
                context.JK.refreshMusicSession(session_id);
            },
            error: app.ajaxError
        });
    };

 })(window,jQuery);