var w = null, text = null, arr = null, max = null;
var current = 0;
var current_id = null;
function getRandomSentence() {
var random = [
"Caca culo pedo pis.",
"Tu culo huele mal.",
"Este cuento es muy tonto.",
"Yo no quiero leer más, déjame en paz.",
"Baila con el culo, baila con el pito."
];
var l = random.length;
var i = dice(l);
return randomi?;
}
function dice(faces) {
var i = Math.floor((Math.random() * faces));
return i;
}
$('.read').hide()
$('.cuento').each( function() {
   var title =  $(this).attr('name');
   var cid =  $(this).attr('id');
   var bid = cid + "_btn";
   $('#menu').append('<a id="' + bid + '" href="#" class="button menu_btn">' + title +'</a>');
   $('#' + bid).click( function() {
       w = $("#" + cid);
       text = w.text().trim();
       arr = text.split(/\.\n?+/gm);
       // arr = text.split(/\.\n?+/);
       max = arr.length -1 ;
       current = app.Load Number?('pag_' + cid, 0);
       current_id = cid;
       $('#menu').hide();
       $('.read').show();
       setPage();
   });
});
function setPage() {
   if (current < 0) {
     current = 0;
     $('#menu').show();
     $('.read').hide();
     return;
   }
   if (current > max ) {
     current = 0;
   }
   var t = arrcurrent?.trim();
   if (/.*a-z?$/.test(t)) {
       // Add a dot if necessary:
       t = t + '.';
   }
   $('#texto').text(t);
   app.Save Number?('pag_' + current_id, current);
   $('#pageCnt').text(current + 1);
}
$('#pageCnt').click(function() {
current = 0;
setPage();
});
$('#next').click(function() {
current++;
setPage();
});
$('#prev').click(function() {
current--;
setPage()
});
$('#texto').click(function() {
var pitch = 1.0, speed = .6;
var read = arrcurrent? + ".";
read = read.replace("- ", "");
if (!dice(6)) {
// One in every few cases, we also read a random sentence :-)
read = read + " " + getRandomSentence();
}
app.Text To Speech?( read, pitch, speed );
});