// defines session-centric websocket code
(function(context, $) {

    "use strict";

    var jamsocket = {};

    function debug_print(msg, inner) {
        var msg_div = $("<div style='margin-top:20px; border-width:0 0 1px; border-color:#ccc; border-style:solid'>");
        var msg_header = $("<h4 style='margin-bottom:2px'>").text(msg.type);
        msg_div.append(msg_header);

        var list = $("<dl style='margin-left:20px; margin-top:0'>");
        msg_div.append(list);

        for (var key in inner) {
            list.append($("<dt>").text(key));
            list.append($("<dd>").text(inner[key]));
        }


        $("#internal_session_activity").append(msg_div);
    }

    jamsocket.init = function() {

        function send(msg) {
            ws.send(context.JSON.stringify(msg));
        }

        // Let the library know where WebSocketMain.swf is:
        context.WEB_SOCKET_SWF_LOCATION = "assets/flash/WebSocketMain.swf";

        var mf = context.message_factory;

        // Write your code in the same way as for native WebSocket:
        var ws = new context.WebSocket(context.gon.websocket_gateway_uri);
        ws.onopen = function() {
            var token = $.cookie("remember_token");
            // there is a chance the token is invalid at this point
            // but if it is, login should fail, and we can catch that as an error
            // and deal with it then.
            $("#internal_session_activity").children().remove();
            var login = mf.login_with_token(token);
            send(login);
        };
        ws.onmessage = function(e) {
            var msg = JSON.parse(e.data);
            var inner = msg[msg.type.toLowerCase()];

            debug_print(msg, inner);

            if(msg.type == context.JK.MessageType.LOGIN_ACK) {
                // we are in... sign in to jam session

                var login_jam = mf.login_music_session(context.gon.music_session_id);
                send(login_jam);
            }
        };
        ws.onclose = function() {
            context.alert("websocket connection closed");
        };
    };

    context.jamsocket = jamsocket;
})(window, jQuery);