(function() {
    var url = '/jbingo.py';

    function remote(args, sync) {
        $.ajax({
            url: url,
            async: !sync,
            data: args,
            type: 'post'
        });
    };

    function register_conversion(conversion) {
        remote({ 'do': 'conversion', id: get_id(), conversion: conversion }, true);
    };

    function get_id() {
        var gen = function() {
            return ('1' + Math.random()).replace('.', '');
        };

        var k = 'jbingo:id';
        var id = window.localStorage[k];
        if (!id) {
            id = window.localStorage[k] = gen() + gen();
        }
        return id;
    };

    function pick_alternative(test, id) {
        var hash = 0;
        for (var i = 0; i < test.length; i++) {
            hash = hash ^ test.charCodeAt(i);
        }
        hash = hash % 10;
        return id[id.length - (hash + 1)] < 5;
    };

    function register_test(testname, conversion) {
        var id = get_id();
        var alt = pick_alternative(testname, id);
        remote({ 'do': 'test', id: id, alternative: alt, test: testname, conversion: conversion });
        return alt;
    };

    window.jbingo = function(testname, conversion) {
        if (!conversion) {
            register_conversion(testname);
        } else {
            return register_test(testname, conversion);
        }
    };
})();

