var pageNumber = 0;
var hidden = 0;
var begin = {{verse-begin}};
var bookChapter = {{book-chapter}};
var bibleText = {{bible-verses}};
var overridedKeys = [36, 35, 66, 87, 13, 32, 34, 39, 40, 33, 37, 38];
var combineKeys = "";

function displayPage(number) {
    document.getElementById('book-chapter').innerHTML = bookChapter + ": " + (number + begin);
    document.getElementById('bible-verses').innerHTML = bibleText[number];
    document.getElementById('page-number').innerHTML = number + 1;
};

function scrollPage(direction) {
    if (direction == 0 && (pageNumber + 1) < bibleText.length) {
        pageNumber ++;
    }
    else if (direction == 1 && (pageNumber - 1) >= 0) {
        pageNumber --;
    }
    displayPage(pageNumber);
};

function goToPage(number) {
    number = parseInt(number);
    if (number >= 1 && number <= bibleText.length) {
        displayPage(number -1);
    }
    else if (number > bibleText.length) {
        displayPage(bibleText.length -1);
    }
};

$(document).keydown(function(event) {
    if (overridedKeys.indexOf(event.which) > -1) {
        event.preventDefault(); 
    }
});

$(document).mousedown(function(event) {
    if (event.which === 1) {
        scrollPage(0);
    }
});

$(document).mousewheel(function(event, delta) {
    event.preventDefault(); 
    if (delta < 0) {
        scrollPage(0);
    }
    else if (delta > 0) {
        scrollPage(1);
    }
});

$(document).keyup(function(event){
    //alert(event.which);
    if (event.which >= 48 && event.which <= 57) {
        combineKeys = combineKeys + String.fromCharCode(event.which);
    }
    if (event.which >= 96 && event.which <= 105) {
        combineKeys = combineKeys + String.fromCharCode(event.which);
    }
    if (event.which == 66 || event.which == 87) {
        if (hidden == 0) {
            hidden = 1;
            $("div").hide();
            combineKeys = "";
        }
        else {
            hidden = 0;
            $("div").show();
            combineKeys = "";
        }
    }
    if (event.which == 32 || event.which == 34 || event.which == 39 || event.which == 40) {
        scrollPage(0);
        combineKeys = "";
    }
    if (event.which == 13) {
        if (combineKeys == "") {
            scrollPage(0);
        }
        else {
            goToPage(combineKeys);
        }
        combineKeys = "";
    }    
    if (event.which == 33 || event.which == 37 || event.which == 38) {
        scrollPage(1);
        combineKeys = "";
    }
    if (event.which == 36) {
        goToPage(1);
        combineKeys = "";
    }
    if (event.which == 35) {
        goToPage(bibleText.length);
        combineKeys = "";
    }
    //else{alert(event.which);}
});

$(document).ready(function() {
    goToPage(1);
});