//<![CDATA[

function getHighestRow() {
    var i = 1;
    while ($('#row' + i).length > 0) {
        ++i;
    }
    return i - 1;
}

function deleteARow() {
    var row = parseInt($(this).attr('id').substring(6));
    $('#row' + row).remove();
    // Adjust row numbers
    var allRows = $('#dataTable tr');
    var rowIndex = 1;
    var firstTime = true;
    allRows.each(function() {
        if (firstTime) {
            firstTime = false;
            return;
        }
        this.id = 'row' + rowIndex;
        $('.expected', this).attr('id', 'expected' + rowIndex);
        $('.actual', this).attr('id', 'actual' + rowIndex);
        $('.delete', this).attr('id', 'delete' + rowIndex);
        ++rowIndex;
    });
    $('.delete').unbind();
    $('.delete').click(deleteARow);
    // Hide delete button if necessary
    if (getHighestRow() <= 2) {
        $('.delete').hide();
    }
}

$(document).ready(function() {
    $('#addRowButton').click(function() {
        var i = getHighestRow() + 1;
        $('#dataTable').append('<tr id="row' + i + '"><td><input type="text" class="expected" id="expected' + i + '" value="100"></td><td><input type="text" class="actual" id="actual' + i + '" value="10"></td><td><input type="button" value="Delete row" class="delete" id="delete' + i + '"></td></tr>');
        $('.delete').unbind();
        $('.delete').show();
        $('.delete').click(deleteARow);
    });

    $('#doBinomial').click(function() {
        var percentages = [];
        var nums = [];
        var i = 1;
        while ($('#expected' + i).length > 0) {
            percentages.push(parseFloat($('#expected' + i).val()));
            nums.push(parseFloat($('#actual' + i).val()));
            ++i;
        }
        var total = 0.0;
        for (var i in percentages) {
            total += percentages[i];
        }
        var factor = 100.0/total;
        percentages = jQuery.map(percentages, function(p) { return factor * p; });
        $.ajax({
            type: 'GET',
            url: statScriptName,
            data: {'percentages': percentages, 'nums': nums},
            dataType: 'json',
            success: doBinomialSuccess,
            error: doBinomialError
        });
    });
});

function doBinomialSuccess(data) {
    var prob = parseFloat(data['prob']);
    if (prob < 0.05) {
        html = 'Yes';
        dataClass = 'sig';
    } else {
        html = 'No';
        dataClass = 'notSig';
    }
    html += ' (chi-squared p=' + prob + ')';
    $('#binomialResult').html(html);
    $('#binomialResult').removeClass('sig').removeClass('notSig').addClass(dataClass);
    $('#binomialAuxData').html('(variance is ' + data['variance'] + ' with ' + data['degreesOfFreedom'] + ' degrees of freedom)');
}

function doBinomialError(data) {
    $('#binomialResult').html('<b>Error!</b>');
    $('#binomialAuxData').html();
}

//]]>
