var baseURL = 'http://localhost:3000';

var coffeeColours = ['#522900', '#372819', '#4B3D30', '#522900', '#755433'];
var colourIndex = 0;

var tally = {};
var recentCoffees = [];
var coffeePrice = 0;
var reader;

$(document).ready(function () {

    // Set up reader that listens for card swipes
    reader = new Reader();
    reader.callback = addCoffee;

    // Get coffee price and user list from server
    console.log("Fetching user list");
    $('#chart').html('Loading users...');

    $.ajax({
        url: baseURL + '/price',
        success: function(price){
            coffeePrice = price;
            $.ajax({
                url: baseURL + '/users',
                success: function(users){
                    tally = {};

                    for(var i = 0; i < users.length; i++)
                        tally[users[i]['card_id']] = {name: users[i]['name'], qty: users[i]['total_coffees']};

                    render();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    new Popup('Error loading user list').open();
                }
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            new Popup('Error getting coffee price').open();
        }
    });

    // Button behaviour
    $('#check-button').click(function () {
        displayBalance();
    });
});

function render() {
    // Render "highscore" chart
    chart = '<table><tr><th>Name</th><th>Qty</th><th>Cost</th></tr>';
    for(var key in tally) {
        chart += '<tr id="' + key + '">' +
            '<td>' + tally[key]['name'] + '</td>' +
            '<td>' + tally[key]['qty'] + '</td>' +
            '<td>£' + cost(parseInt(tally[key]['qty'])) + '</td>' +
            '</tr>'
    }
    chart += '</table>';

    $('#chart').html(chart);

    // Render recent coffee list
    var recent = $('#recent');
    recent.html('');
    for(var i = 0; i < recentCoffees.length; i++) {
        recent.prepend(recentCoffee(recentCoffees[i].name, recentCoffees[i].number));
    }
}

function cost(qty) {
    return (qty * coffeePrice).toFixed(2)
}

function recentCoffee(name, number) {
    var date = new Date();
    var colour = coffeeColours[colourIndex++ % coffeeColours.length];
    return '<div class="recent-coffee" style="border-color: ' + colour + '">' +
        name + ' #' + number + '<br/><em>' + date.toUTCString().slice(0,-3) + '</em></div>';
}

function addCoffee(id) {
    $.ajax({
        type: "POST",
        url: baseURL + '/users/' + id + '/coffees',
        success: function(coffee){
            tally[id].qty += 1;
            colourIndex++;

            recentCoffees.push({name: tally[id].name, number: tally[id].qty});
            if(recentCoffees.length > 5)
                recentCoffees.shift();

            var popup = new Popup(tally[id].name + ' +1 <br/>(' + tally[id].qty + ' total)', 2000);

            popup.onOpen = function () {
                reader.disable();
            };

            popup.onClose = function () {
                reader.enable();
            };

            popup.open();
            render();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            new Popup(errorThrown, 1000).open();
        }
    });
}

function displayBalance() {
    var popup = new Popup('Swipe your card');
    var cb;

    popup.onOpen = function () {
        cb = reader.callback;
        reader.callback = function (id) {
            if(tally[id] != null)
                popup.setMessage('<strong>' + tally[id].name + '</strong><br/>Coffees: ' + tally[id].qty + '<br/>Balance: £' + cost(tally[id].qty));
            else
                popup.setMessage('Invalid ID');
        };
    };

    popup.onClose = function () {
        reader.callback = cb;
    };

    popup.open();
}

@@ -1494,21 +1494,8 @@
 th%3E%3C
-th%3ECost%3C/th%3E%3C
 /tr%3E
@@ -1675,76 +1675,8 @@
 ' +%0A
-            '%3Ctd%3E%C2%A3' + cost(parseInt(tally%5Bkey%5D%5B'qty'%5D)) + '%3C/td%3E' +%0A
     
@@ -3394,16 +3394,21 @@
 nction (
+card_
 id) %7B%0A  
@@ -3421,63 +3421,156 @@
     
-if(tally%5Bid%5D != null)%0A                popup.setMessage(
+$.ajax(%7B%0A                url: baseURL + '/users/' + card_id + '/balance',%0A                success: function(balance)%7B%0A                    var msg = 
 '%3Cst
@@ -3580,24 +3580,29 @@
 g%3E' + tally%5B
+card_
 id%5D.name + '
@@ -3626,32 +3626,37 @@
 fees: ' + tally%5B
+card_
 id%5D.qty + '%3Cbr/%3E
@@ -3668,52 +3668,343 @@
 ce: 
-%C2%A3' + cost(tally%5Bid%5D.qty));%0A            else%0A
+';%0A                    if(balance %3C 0)%0A                        msg += '%3Cspan style=%22color: red%22%3E%C2%A3' + balance + '%3C/span%3E';%0A                    else%0A                        msg += '%C2%A3' + balance;%0A%0A                    popup.setMessage(msg);%0A                %7D,%0A                error: function(XMLHttpRequest, textStatus, errorThrown) %7B%0A    
     
@@ -4043,24 +4043,58 @@
 valid ID');%0A
+                %7D%0A            %7D);%0A
         %7D;%0A 

Check balance against server