// Define global variables
var audiohome = "http://springbible.fhl.net/Bible2/Audio/RCUV/";
var nowbook = 0;
var nowchapter = 0;
var cchapter;
var readedchapter = new Array();
var cnums=new Array(50,40,27,36,34,24,21,4,31,24,22,25,29,36,10,13,10,42,150,31,12,8,66,52,5,48,12,14,3,9,1,4,7,3,3,3,2,14,4, 28,16,24,21,28,16,16,13,6,6,4,4,5,3,6,4,3,1,13,5,5,3,5,1,1,1,22);
var day_plan = new Array();
var everyday_chapter1;

function endofvoice(bnum, cn) {
	if(everyday_chapter1.value == 0){
		everyday_chapter1.value = -1;
	} else {
		setchap1(Reading, bnum, cn);
	}
}

function setchap1(f, bnum, cn) {
        var i,j,k,txt;
	
	var currentchapters = cn;
	
	if (cn == -1) {
		bnum--;
		cn = cnums[bnum] - 1;
	}
	if (cn == cnums[bnum]) {
		bnum++;
		cn = 0;
	}
	i=cnums[bnum];

	if(i == 150)
	  for(j = 1; j <= 150;j++) {
	    txt = "第 " + j + " 篇";
	    f.chap.options[j-1] = new Option(txt, j);	
	  }
	else if(i < 150){
	  for(j = 1; j <= i; j++) {
	    txt = "第 " + j + " 章";
	    f.chap.options[j-1] = new Option(txt, j);
	  }
	  for(j = 150;j > i;j--)
	    f.chap.options[j-1] = null;
	}

	f.chap.options[0].selected = cn;
	readchapter(bnum, cn);
}

function readchapter(bnum, cnum){
	var f = document.getElementById('bibletext');
	cnum = Number(cnum);
	bnum = Number(bnum);
  if((bnum - 0 < 0) || (bnum - 0 >= 66))
    bnum = 0;
  if((bnum - 0 <= 0) && (cnum - 0 < 0))
    cnum = 0;
  if((bnum - 0 >= 65) && (cnum - 0 >=22))
    cnum = 21;
  if(cnum - 0 < 0) {
      bnum--;
      cnum = book_chapters[bnum+1] - book_chapters[bnum]-1;
  }
  if(cnum - 0 >= book_chapters[bnum+1] - book_chapters[bnum]) {
      bnum++;
      cnum = 0;
  }
  nowbook = bnum1 = bnum;
  nowchapter = cnum;
  cnum1 = cnum+1;

  precnum = cnum -1;
  bbnum = bnum;
  if(cnum == 0){
    bbnum = bnum - 1;
    precnum = cnums[bbnum] - 1;
  }
  if((bnum > 0) || (cnum > 0))
    if(bbnum != 18)
      if(cnums[bbnum] > 1)
	temp1 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + precnum+'); return false;">' + books[bbnum] + '第' + numbers[precnum] + '章</a>\n';
      else
	temp1 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + precnum+'); return false;">' + books[bbnum] + '</a>\n';
    else 
	temp1 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + precnum+'); return false;">' + books[bbnum] + '第' + numbers[precnum] + '篇</a>\n';
  else
    temp1 = '';
  
  nextcnum = cnum +1;
  bbnum = bnum;
  if(cnum == cnums[bnum]-1){
    bbnum = bnum + 1;
    nextcnum = 0;
  }
  if(!((bnum == 65)&&(cnum == 21)))
    if(bbnum != 18)
      if(cnums[bbnum] > 1)
	temp2 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + nextcnum+'); return false;">' + books[bbnum] + '第' + numbers[nextcnum] + '章</a>\n';
      else
	temp2 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + nextcnum+'); return false;">' + books[bbnum] + '</a>\n';
    else
	temp2 = '<a href="" onClick="setchap1(Reading, ' + bbnum + ',' + nextcnum+'); return false;">' + books[bbnum] + '第' + numbers[nextcnum] + '篇</a>\n';
  else
    temp2 ='';

  chapter_number = 'RCUV-' + Number(book_chapters[bnum]+cnum);
  readedchapter[book_chapters[bnum]+cnum] = 1;
  everyday_chapter1 = document.getElementById("RCUV-everyday");
  if ((localStorage.getItem(chapter_number) == null) || (localStorage.getItem(chapter_number) == 0)){
	everyday_chapter1.value--;
  }
  localStorage.setItem(chapter_number, 1);

  out1 = document.getElementById("audio1");
  out1.innerHTML = '';
  bnum1 = bnum + 1;
  cnum1 = cnum + 1;
  if(bnum1 < 10)
    temp10 = '0' + bnum1 + '_';
  else
    temp10 = bnum1 + '_';
  if(cnum1 < 10)
     temp10 = temp10 + '00' + cnum1 + '.mp3';
  else if (cnum + 1 < 100)
     temp10 = temp10 + '0' + cnum1 + '.mp3';
  else 
     temp10 = temp10 + cnum1 + '.mp3';
  temp11 = audiohome + temp10;
  autos = document.getElementById("auto1");
  out4 = document.createElement("audio");
  out5 = document.createElement("source");
  out5.setAttribute("src", temp11);
  out5.setAttribute("type", "audio/mp3");
  out4.appendChild(out5);
  out4.setAttribute("controls", "controls");
  out4.setAttribute("preload", "auto");
  if((autos.checked == true) && (everyday_chapter1.value >= 0)){
//  if(autos.checked == true){
    out4.setAttribute("autoplay", "autoplay");
    temptemp = 'endofvoice(' + bbnum + ',' + nextcnum + ')';
    if(everyday_chapter1.value >= 0)
	out4.setAttribute("onended", temptemp);
  }
  out1.appendChild(out4);
  

  tempNode1 = document.getElementById("link2");
  tempNode1.innerHTML = "";
  tempNode1.innerHTML += temp1;
  tempNode1.innerHTML += "<br>";
  tempNode1.innerHTML += temp2;

  f.src = "http://bible.fhl.net/new/read.php?VERSION4=rcuv&TABFLAG=0&chineses=" + simplebooks[bnum] + "&chap=" + cnum1;
	readedchapter[book_chapters[bnum]+cnum] = 1;
	chapter_number = 'RCUV-' + Number(book_chapters[bnum]+cnum);
	localStorage.setItem(chapter_number, 1);

	j = Number(book_chapters[bnum] + cnum1);
	first_chapter = document.getElementById("firstchapter");
	first_chapter.innerHTML = Number(chapter_lines[j]-chapter_lines[j-1]) + '節　';

	book_selet = document.getElementById("book1");
	book_selet.selectedIndex = bnum;
	chapter_selet = document.getElementById("chapter1");
	chapter_selet.selectedIndex = cnum;
	cchapter = book_chapters[bnum]+cnum;
	countchapter();
}

function process_percentage(){
	var bb = 0;
	if(typeof(Storage)=="undefined") return;

	var outs = document.getElementById("RCUV-start1");
	var outf = document.getElementById("RCUV-finish1");
	var outd = document.getElementById("RCUV-duration");
	var dd = new Date();
	var year = dd.getFullYear();
	var Sdate = new Date();
	Sdate.setTime(0);
	Sdate.setFullYear(year);
	Sdate.setMonth(dd.getMonth());
	Sdate.setDate(dd.getDate());
	var start1 = Sdate.getTime();
	if (localStorage.getItem("RCUV-start1") != null)
		start1 = localStorage.getItem("RCUV-start1");
	Sdate.setTime(start1);
	var Fdate = new Date();
	Fdate.setTime(0);
	Fdate.setFullYear(Sdate.getFullYear()+1);
	Fdate.setMonth(dd.getMonth());
	Fdate.setDate(dd.getDate());
	var finish1 = Fdate.getTime();
	var duration = finish1 - start1;
	if (localStorage.getItem("RCUV-duration") != null)
		duration = localStorage.getItem("RCUV-duration");
	finish1 = Number(start1) + Number(duration);
	Fdate.setTime(Number(finish1));
	Sdate.setTime(start1);
	localStorage.setItem("RCUV-start1", start1);
	localStorage.setItem("RCUV-duration", duration);
	outd.value = Math.ceil(duration/86400000);
	outs.value = Sdate.toISOString().substr(0, Sdate.toISOString().indexOf("T"));
	outf.value = Fdate.toISOString().substr(0, Fdate.toISOString().indexOf("T"));
	var now1 = dd.getTime();
	var days = Math.floor((now1-start1)/86400000) + 1;
	var fchapter = new Date(), fline = new Date(), flength = new Date();
	var fudays = Math.ceil((Number(finish1) - Number(now1))/86400000);
	
	readedC = 0;
	readedClines = 0;
	readed_length = 0;
	for(var i = 0;i < 1189;i++){
		chapter_number = 'RCUV-' + Number(i);		
		readedchapter[i] = localStorage.getItem(chapter_number);
		if (readedchapter[i] == 1){
		    readedC++;
		    readedClines += chapter_lines[i+1] - chapter_lines[i];
		    readed_length += chapter_length[i];
		}
	}
	num1 = readedC/1189 * 100;
	num2 = readedClines/31102 * 100;
	if(days > 0)
		num3 = readedC/days;
	else
		num3 = readedC;
	num4 = readed_length / total_length * 100;
	if(duration == 0) duration = 1;
	num5 = (now1 - start1) / duration * 100;
	percentage = document.getElementById("percentage");
	percentage.style.color = "black";
//	percentage.style.fontSize = "24";
	percentage.style.textAlign = "left";
	percentage.innerHTML = '共讀 ' + readedC + ' 章，\n';
	percentage.innerHTML += '章：' + num1.toFixed(2) + '%，\n';
	percentage.innerHTML += '節：' + num2.toFixed(2) + '%\n';
	percentage.innerHTML += '長度：' + num4.toFixed(2) + '%\n';
	percentage.innerHTML += '時間：' + num5.toFixed(2) + '%<br>\n';
	if(fudays > 0)
		num1 = (1189 - readedC)/fudays;
	else
		num1 = 1189 - readedC;
	num2 = 1189 / duration * 86400000;
	percentage.innerHTML += '共' + days + '天,每天應：' + num2.toFixed(2) + ' 實際：'+ num3.toFixed(2) + ' 章\n';
	percentage.innerHTML += ' 未來每天：' + num1.toFixed(2) + ' 章<br>\n';
	if(readedC == 0) readedC = 1;
	if(readedClines == 0) readedClines = 1;
	if(readed_length == 0) readed_length = 1;
	fchapter.setTime(Number(start1) + (now1-start1) *1189/ readedC);
	fline.setTime(Number(start1) + (now1-start1) * 31102 / readedClines);
	flength.setTime(Number(start1) + (now1-start1) * total_length / readed_length);
	percentage.innerHTML += '預估完成日期 \n';
	percentage.innerHTML += '章：' + fchapter.toISOString().substr(0, fchapter.toISOString().indexOf("T"));
	percentage.innerHTML += ' 節：' + fline.toISOString().substr(0, fline.toISOString().indexOf("T"));
	percentage.innerHTML += ' 長度：' + flength.toISOString().substr(0, flength.toISOString().indexOf("T")) + '<br>\n';
	
	percentage.innerHTML += '尚未讀的有：\n';
	percentage.innerHTML += '(<a href="" onClick="reset1(); return false;">清除所有記錄</a>, <a href="" onClick="unread(' + cchapter + '); return false;">本章設為未讀</a>)\n';

	out3 = document.createElement("ol");
	percentage.appendChild(out3);
	OK = 0;
	for(var i = 0;i < 66;i++){
		for(var j = book_chapters[i];j < book_chapters[i+1];j++)
		  if(readedchapter[j] != 1) {
			num1 = j - book_chapters[i];
			num2 = num1+1;
			bbb = books[i];
			if(OK == 0){
				out4 = document.createElement("li");
				out3.appendChild(out4);
				OK = 1;
				out4.innerHTML += '<a href="" onClick="setchap1(Reading, ' + i + ',' + num1 + '); return false;">' + books[i] + ' ' + num2 +'</a>～';
			}
		  } else {
			if((OK == 1)&&(j > 0))
				out4.innerHTML += bbb + num2 + '\n';
			if(OK == 1)
			  OK = 0;
		  }
	}
	if(readedchapter[1188] != 1){
		out4.innerHTML += bbb + num2 + '\n';
	}

	first_chapter = document.getElementById("firstchapter");
	for(i = 0;i < 66;i++)
	   for(j = book_chapters[i];j < book_chapters[i+1];j++)
		if(readedchapter[j] != 1) {
		   numa = j - book_chapters[i];
		   numb = numa + 1;
		   first_chapter.innerHTML += '<a href="" onClick="setchap1(Reading, ' + i + ',' + numa + '); return false;">' + books[i] + ' ' + numb +'</a>';
		   return;
		}
}

function unread(chapter){
	if(typeof(Storage)=="undefined") return;
	readedchapter[chapter] = 0;
	chapter_number = 'RCUV-' + Number(chapter);
	localStorage.setItem(chapter_number, 0);
	countchapter();
}

function reset1(){
	if(typeof(Storage)=="undefined") return;
	for(var i = 0;i < 1189;i++){
		chapter_number = 'RCUV-' + Number(i);
		localStorage.setItem(chapter_number, 0);
	}
	countchapter();
}

function changeS(){
	if(typeof(Storage)=="undefined") return;
	var duration = localStorage.getItem("RCUV-duration");
	var outs = document.getElementById("RCUV-start1");
	var outf = document.getElementById("RCUV-finish1");
	var ss = outs.value;
	var dd = ss.split("-");
	var Sdate = new Date(Number(dd[0]), Number(dd[1])-1, Number(dd[2])+1, 0, 0, 0, 0);
	var start1 = Sdate.getTime();
	localStorage.setItem("RCUV-start1", start1);
	var finish1 = Number(start1) + Number(duration);
	var Fdate = new Date();
	Fdate.setTime(finish1);
	outf.value = Fdate.toISOString().substr(0, Fdate.toISOString().indexOf("T"));
	countchapter();
}

function changeD(){
	if(typeof(Storage)=="undefined") return;
	var start1 = localStorage.getItem("RCUV-start1");
	var outd = document.getElementById("RCUV-duration");
	var outf = document.getElementById("RCUV-finish1");
	var du = outd.value;
	var duration = Number(du) * 86400000;
	localStorage.setItem("RCUV-duration", duration);
	var finish1 = Number(start1) + Number(duration);
	var Fdate = new Date();
	Fdate.setTime(finish1);
	outf.value = Fdate.toISOString().substr(0, Fdate.toISOString().indexOf("T"));
	countchapter();
}

function changeF(){
	if(typeof(Storage)=="undefined") return;
	var start1 = localStorage.getItem("RCUV-start1");
	var outd = document.getElementById("RCUV-duration");
	var outf = document.getElementById("RCUV-finish1");
	var ff = outf.value;
	var dd = ff.split("-");
	var Fdate = new Date(Number(dd[0]), Number(dd[1])-1, Number(dd[2])+1, 0, 0, 0, 0);
	var finish1 = Fdate.getTime();
	var duration = Number(finish1) - Number(start1);
	localStorage.setItem("RCUV-duration", duration);
	outd.value = Math.ceil(duration/86400000);
	countchapter();
}

function everyday(){
	if(typeof(Storage)=="undefined") return;
	var chapter1 = document.getElementById("RCUV-everyday");
	var Now1 = new Date();
	var now1 = Now1.getTime();
	if((chapter1.value >= 1) && (chapter1.value <= 100)) {
	    localStorage.setItem("RCUV-everyday", chapter1);
	    localStorage.setItem("RCUV-savedtime", now1);
	}
}

function linkunreaded(remaind1, bn1, cn1){
	everyday_chapter1 = document.getElementById("RCUV-everyday");
	everyday_chapter1.value = remaind1;
	autos = document.getElementById("auto1");
	autos.checked = true;
	setchap1(Reading, bn1, cn1);
}

function countchapter() {
        var i,j,k,txt, current_length, bnum1, cnum1, bnum2, cnum2, previous_length;
	var outfield = document.getElementById('plan');
	var unreadday = 0;
	
	process_percentage();
	if (localStorage.getItem("RCUV-start1") != null)
		start1 = localStorage.getItem("RCUV-start1");
	if (localStorage.getItem("RCUV-duration") != null)
		duration = localStorage.getItem("RCUV-duration");

	var time1 = new Date();

	days = Math.ceil(duration/86400000);
//	temp1_1 = document.getElementById("test");
//	temp1_1.innerHTML = "days=" + days + "<br />\n";

//	day_length = total_length / days;
	previous_length = current_length = 0;
	j = 0;
	for(i = 0;i < 1189;i++){
	  if(current_length >= total_length / days *j){
//	     plan_number = 'C1-Plan-' + Number(j);
//	     localStorage.setItem(plan_number, i);
	     day_plan[j++] = i;
	  }
	  current_length += chapter_length[i];
	}
	day_plan[j] = 1189;
	
	for(i = 0;i < 1189;i++)
	  if(readedchapter[i] != 1){
		firstunreaded = i;
		break;
	  }

	for(i = 0;i < days;i++)
	  if(day_plan[i] >= firstunreaded){
	    unreadday = i;
	    break;
	  }
	  
	outfield.innerHTML = '';
	bnum1 = cnum1 = 0;
	k = 0;//k 代表目前到哪一卷書
	for(i = 0;i < unreadday+5;i++){
//	for(i = 0;i < days;i++){
	    k1 = k;
	    while(book_chapters[k+1] < day_plan[i+1])
	      k++;
	    bnum2 = k;
	    cnum2 = day_plan[i+1] - book_chapters[k] - 1;
	    time1.setTime(Number(start1) + i*86400000);
	    date1 = time1.toISOString().substr(0, time1.toISOString().indexOf("T"));
	    if(day_plan[i+1] > firstunreaded) {
	      if(day_plan[i] <= firstunreaded){
		while(book_chapters[k1+1] <= firstunreaded)
		  k1++;		
//		linkunreaded(day_plan[i+1] - firstunreaded, k1, firstunreaded - book_chapters[k] - 1);
//		outfield.innerHTML += 'firstunreaded=' + firstunreaded + 'book_chapters[k1]='+ book_chapters[k1] + '<br>\n';

		if(cnums[k1] > 1)
		  outfield.innerHTML += date1 + '\t' + '<a href="" onClick="linkunreaded(' + Number(day_plan[i+1] - firstunreaded) + ',' + k1 + ',' + Number(firstunreaded - book_chapters[k1]) + '); return false;">' + simplebooks[k1] + Number(firstunreaded - book_chapters[k1]+1) + '</a>-';
//		  outfield.innerHTML += simplebooks[bnum1] + Number(cnum1+1) + '</a>-';
		else
		  outfield.innerHTML += date1 + '\t' + '<a href="" onClick="linkunreaded(' + Number(day_plan[i+1] - firstunreaded) + ',' + k1 + ',' + Number(firstunreaded - book_chapters[k1] - 1) + '); return false;">' + simplebooks[k1] + '</a>-';
//		  outfield.innerHTML += simplebooks[bnum1] + '</a>-';
		if(cnums[bnum2] > 1)
		  outfield.innerHTML += simplebooks[bnum2] + Number(cnum2+1) + '<br />\n';
		else
		  outfield.innerHTML += simplebooks[bnum2] + '<br />\n';

	      } else {
		if(cnums[bnum1] > 1)
		  outfield.innerHTML += date1 + '\t' + simplebooks[bnum1] + Number(cnum1+1) + '-';
		else
		  outfield.innerHTML += date1 + '\t' + simplebooks[bnum1] + '-';
		if(cnums[bnum2] > 1)
		  outfield.innerHTML += simplebooks[bnum2] + Number(cnum2+1) + '<br />\n';
		else
		  outfield.innerHTML += simplebooks[bnum2] + '<br />\n';
	      }
	    }
	    
	    if(day_plan[i+1] >= book_chapters[k+1]){
	      bnum1 = bnum2+1;
	      cnum1 = 0;
	    } else {
	      bnum1 = bnum2;
	      cnum1 = cnum2 + 1;
	    }
	}
}
