/**
 * (c) 2011, 2012 Chani Armitage <chanika@gmail.com>
 * TODO: license
 */

//book vars
var prefix, digits;
function initAudio(p, d) {
    prefix=p;
    digits=d;
}

$(document).ready(function() {
    //embed the html
    //FIXME I'd like a less ugly way...
    //maybe div.load(controls.html)...
    $('body').prepend("<div id='controls'><input type='button' id='prev' value='<<' /><audio id='audio' controls='controls'></audio><input type='button' id='next' value='>>' /></div><br /><br />");
    
    //multi-file support
    var chapter = 1;
    var audio = document.getElementById('audio');
    var loadChapter = function() {
        var file = prefix;
        //add leading zeros
        var bar = Math.pow(10, digits-1);
        while (chapter < bar) {
            file += '0';
            bar /= 10; //chapter better not be <1.
        }
        file += chapter + ".mp3";
        audio.src = file;
        audio.play();
    }
    var nextChapter = function() {
        chapter++;
        loadChapter();
    }
    var prevChapter = function() {
        if (chapter <= 1) return;
        chapter--;
        loadChapter();
    }
    $('audio').on('ended', nextChapter);
    $('#next').click(nextChapter);
    $('#prev').click(prevChapter);
    loadChapter();
});
