$(document).ready( function() {
    $("#play, #playagain").click( play_game );
} );

function play_game() {
    $("#play, #playagain").hide();
    $("#pending").show();
    $("#results").hide();

    $.ajax({
        url:        "vr.cgi",
        dataType:   "json",
        data:       { stamp: (new Date()).getTime() }, // To trick IE caching
        success:    handle_results,
        error:      do_fail
    });
}

function reset() {
    $("#pending").hide();
    $("#results").show();
    $("#playagain").show();

    $("#resultcaption").removeClass("lose").removeClass("win");
}

function handle_results(data) {
    reset();

    if (data.fail) {
        do_fail();
    } else {
        $("#resultimg").html(
            '<a href="' + data.img.url + '"><img src="' + data.img.src + '"></a>'
        );
        $("#resultimg img")
            .attr('height', data.img.height)
            .attr('width', data.img.width);

        $("#resultdesc").html(
            '<a href="' + data.img.url + '">' + data.img.name + '</a> ' +
            'posted by <a href="' + data.owner.url + '">' + data.owner.name + '</a>'
        );

        $("#resultcaption").html(
            (data.win ? "You win a velociraptor" : "You lose")
        );

        $("#resultcaption").addClass( data.win ? "win" : "lose" );
    }
}

function do_fail() {
    reset();

    $("#resultimg").html('<img src="broken.jpg">');
    $("#resultdesc").html("Our sincerest apologies");
    $("#resultcaption").html("The machine is broken");
}

