$(document).ready(function(){
    $('#starter').prop('disabled', 'disabled');
    $("#error").hide();
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

    function resizeAce() {
        return $('#editor').height($(window).height() - $("#editor").offset().top - 100);
    };

    $(window).resize(resizeAce);
    resizeAce();

    var gorobots = gorobots_init({}, true);

    $("#robot_picker").change(function(e){
        $.ajax({
            url:"/api/v1/bot/" + $("#robot_picker").val(),
            success: function(data){
                editor.setValue(data.code);
                set_current_bot($("#robot_picker").val());
            }
        });
    });

    $('#starter').click(function() {
        $('#tabs a[href="#arena"]').tab('show');
        gorobots.set_spectator(false);
        gorobots.set_server(wsurl(), getGameID());
    });
    $('#watch').click(function() {
        $('#tabs a[href="#arena"]').tab('show');
        gorobots.set_spectator(true);
        gorobots.set_server(wsurl(), getGameID());
    });

    $('#tabs a[href="#code"]').tab('show');

    $("#fetch-url").keydown(function(e){
        if(e.keyCode == 13 || e.keyCode == 32){
            loadCode();
        }
    });
    $("#fetch-button").click(loadCode);
});

function loadCode() {
    var url = $("#fetch-url").val();
    $.get(url).success(function(e) {
        $("#error").val(e).hide();
        editor.setValue(e);
        $("#editor").show();
        $("#fetch-area").hide();
        $('#starter').prop('disabled', '');
    }).fail(function(e){
        var msg = "got a useless error message; is the remote server down?";
        if (e.statusText != "error") {
            msg = e.responseText;
        }
        $("#error").text(msg).show();
    });
}

function wsurl() {
    var url = "ws://";
    if(window.location.protocol == "https:") {
        url = "wss://";
    }
    url = url + window.location.host + "/ws/";
    return url; 
}

function getGameID() {
    return window.location.search.split("=")[1];
}
