if (Orbited == undefined) throw "Orbited.js must be included before network.js"

Orbited.TCPSocket.prototype.readPacket = function(data) {
    if (this.buf == undefined) {
        this.buf = "";
    }
    var delim = -1;
    while ((delim = data.indexOf("\0")) != -1) {
        this.buf += data.substr(0, delim);
        data = data.substr(delim + 1);
        var s = this.buf.indexOf("{");
        var jsn = this.buf.substr(s);
        this.onpacket(Number(this.buf.substr(0, s)), jsn);
        this.buf = "";
    }
    this.buf += data;
}

Orbited.TCPSocket.prototype.sendPacket = function(id, data) {
    this.sendPacketString(id, JSON.stringify(data));
}

Orbited.TCPSocket.prototype.sendPacketString = function(id, data) {
    if (this.readyState != this.READY_STATE_OPEN) return;
    this.send(String(id) + data + "\0");
}

var socket = new Orbited.TCPSocket();
var connectCallback = null;

function connect(cb) {
    if (socket == null) { socket = new Orbited.TCPSocket(); }
    if (socket.readyState == 3) return true;
    if (socket.readyState != 1) { socket.reset(); socket = new Orbited.TCPSocket(); }
    if (cb !== undefined) {
	connectCallback = cb;
    }
    
    socket.onread = socket.readPacket;
    
    socket.onopen = function()
    {
		if (connectCallback != null) connectCallback(true);
		unitysendmessage('content3d', "Com", "ConnectedCallback", "");
    }

    socket.onclose = function(code) {
		socket = null;
		unitysendmessage('content3d', "Com", "DisconnectedCallback", "");
    }

    socket.onpacket = function(id, datastr) {
		try {
			if (id == 5) {
				var data = JSON.parse(datastr);
				if (data.id) {
					$.cookie('lastroom', String(data.id), {expires: 7});
				}
			}
		} catch (ex) {}
		
        unitysendmessage('content3d', "Com", "Data", String(id) + datastr);
    }
    
    socket.open("localhost", gsPort, true);
    return false;
}

function isConnected() {
    return ((socket != null) && (socket.readyState == 3));
}

window.onbeforeunload = function() {
    if (socket != null) {
    	socket.onclose = function () {};
        socket.close();
    }
}

