jQuery(document).ready(function() {

if($("body.book-content").length > 0) {
add_blank_book_html();
generate_menu("#menu");}

if (jQuery(".chapter-content").length == 1) {
var id = jQuery(".chapter-content:first").attr("id").substring(2);
jQuery("#co"+id).addClass("chapter");
generate_html_from_content(id,"#co"+id);
currentPosition = 0;
jQuery("#"+id).removeClass("chapter-content");
add_menu_events();
}

	dictant_delay = parseFloat(localStorage["dictant_delay"])||1.5;
	dictant_repeats = parseFloat(localStorage["dictant_repeats"])||2;
	//currentPosition = localStorage["currentPosition"]||1;
	//currentChapter = localStorage["currentChapter"]||1;
	//currentChapter = jQuery(".time:first").attr("id").substring(2)||jQuery(".chapter-content:first").attr("id").substring(2);

open_chapter(currentChapter, currentPosition);
	
});

jQuery(window).bind('beforeunload', function(event) {
	/*
    event.stopPropagation();
    event.returnValue = "Внимание! \n Бла-Бла-Бла!";
    return event.returnValue;
	*/
	localStorage["currentPosition"] = currentPosition;
	localStorage["currentChapter"] = currentChapter;
	localStorage["dictant_delay"] = dictant_delay;
	localStorage["dictant_repeats"] = dictant_repeats;
});

String.prototype.supplant = function(o) {return this.replace(/{([^{}]*)}/g,  function(a, b) { var r = o[b];  return typeof r === 'string' || typeof r === 'number' ? r : a; });};	 

function play_interval(tm) {
		play_mode="phrase";
		var time = tm.split("-");
		t1 = tm.split("-")[0];
		t2 = tm.split("-")[1];
		aud.currentTime=t1;
		aud.play();
		aud.addEventListener('timeupdate', playing_interval_in_player , false);
		}
		
	
function t(time_interval) {
var tt=time_interval.split(",");
		
		var t10 = tt[1].split(":");
		var t20 = tt[2].split(":");
		tt[0] = (parseFloat(t10[2]) + parseFloat(t10[1])*60 + parseFloat(t10[0])*3600).toFixed(2);
		tt[1] = (parseFloat(t20[2]) + parseFloat(t20[1])*60 + parseFloat(t20[0])*3600).toFixed(2);
		return tt;
		
	}



function playing_interval_in_player() {	if((aud.currentTime >= t2)&&(play_mode=="phrase")) aud.pause();	}

function interval_clicked() {
		if (play_mode=="stream"||recent_action != "interval_clicked")cur_time = aud.currentTime;
		recent_action = "interval_clicked";
		if(jQuery("audio").length > 1) aud = document.getElementById('a'+jQuery(this).parent().attr("id").substring(2));
		

		if(aud != undefined){aud.pause(); }
       play_interval(jQuery(this).attr("tm"));

}

function add_player_events () {
	jQuery('#playControl').click(playControl_clicked); 
	jQuery('#pauseControl').click(pauseControl_clicked); 
	jQuery('#forwardControl').click(forwardControl_clicked); 
	jQuery('#backControl').click(backControl_clicked); 
	jQuery('#repeatControl').click(repeatControl_clicked); 
}

 // Управление проигрыванием с клавиатуры в режиме HTML для книги
		jQuery(document).keydown(function(eventObject){

			//if (eventObject.which == 32)
			//{repeatControl_clicked();}
			if (eventObject.which == 39) 
			forwardControl_clicked();
			if (eventObject.which == 37)
			backControl_clicked();
		});


// Управление проигрыванием с клавиатуры в режиме Синхронизации текстов с аудио

/*		jQuery(document).keydown(function(eventObject){

			if (eventObject.which == 39) 
			{
			play_interval(jQuery("#"+"i"+jQuery(aud).attr("id").substring(1)+"_"+(currentPosition+1)).attr("tm"));
			currentPosition++;
			focus_on("#"+"i"+jQuery(aud).attr("id").substring(1)+"_"+currentPosition);
			}
			//forwardControl_clicked();
			if (eventObject.which == 37)
						{
			play_interval(jQuery("#"+"i"+jQuery(aud).attr("id").substring(1)+"_"+(currentPosition-1)).attr("tm"));
			currentPosition--;
			focus_on("#"+"i"+jQuery(aud).attr("id").substring(1)+"_"+currentPosition);
			}
		});
*/		

			var template_audio = '<audio id="a{id}" preload="auto" {controls}><source src="{src_ogg}" type="audio/ogg"><source src="{src_mp3}" type="audio/mpeg"></audio>';
			var template_phrase = '<div class="il" tm="{tm}"><div class="ph-or">{or}</div><div class="ph-tr">{tr}</div><div class="set_cur_pos" title="{phrase_id}"></div></div>\n';
			var template_dict = '<div class="ph-dict">{dict}</div>'; 		

		
function generate_html_from_content(source_id, target) {
			currentChapter = source_id;
			var html_chapter = "";
			var html_dict ="";
			var elem = jQuery("#co"+source_id+".chapter-content").text().trim();

			if(elem) {
				var ca = elem.split("\n"); // ca = content arrey

				html_chapter = template_audio.supplant({id:source_id, controls:"", src_ogg:ca[0],src_mp3:ca[1]});
				var step = 2;
					for (var i = 1; i<= (ca.length - 2)/3; i++){
						var tt = ca[step].split("\n");
						var t1 = tt[0];
						var t2 = tt[1];
						try {
						var tr_and_dict = ca[step+2].split("/");
						var dict_count = tr_and_dict.length-1;
						}
						catch (e) { }
						
						for (var j=1; j<= dict_count; j++){
						
						
						html_dict += template_dict.supplant({dict: tr_and_dict[j]});
						
						
						}
						
						html_chapter += template_phrase.supplant({tm:ca[step], or: ca[step+1], tr: tr_and_dict[0], phrase_id: i});
						html_chapter += html_dict;
						html_dict = "";
						step = step + 3;
					}
				jQuery(target).html(html_chapter);
				$(target)[0].setAttribute("id", source_id);

			}
		// if dictionary content arabic letters , we make they font bigger
		jQuery('.ph-dict').each(function(i,elem) { 		
		jQuery(elem).html(jQuery(elem).html().replace(/([\u0600-\u06FF]+)/g,'<span class="ph-ar">$1</span>')); 
		});
		
		add_player_events();

}




// < PLAYER

//currentPosition = localStorage["currentPosition"] || 0; 
//cur_time = 0; 
play_mode = "stream";
recent_action ="opened";
dictant_cur_repeat =0;
player = '<div class="player"><center><div id="load-progress"></div><div id="slideshow-block">Нажмите "Play" или "Forward"</div><div id="controls-block"><div class="nav-button" id="backControl"><</div><div class="nav-button" id="playControl">Play</div><div class="nav-button" id="pauseControl">Pause</div><div class="nav-button" id="repeatControl">Repeat</div><div class="nav-button" id="forwardControl">></div><div class="nav-button" id="cur-pos-block"></div><div class="nav-button" id="dictantControl">Dictation</div><div id="dictantSettings"><img src="textophone/images/settings.png"></div><div id="dictant-settings">Задержка (<small>длина фразы</small> x)<input id="dictant_delay" class="nav-button"  type="text" value="2"/> повторов: <input class="nav-button"  id="dictant_repeats" type="text" value="2"/><div class="nav-button" id="dictant-settings-change">Применить</div> </div></div></center></div>';



function playControl_clicked() {
if(currentPosition == 0) currentPosition = 1;
if(currentPosition > 1) aud.currentTime = jQuery(jQuery(chapter_id+" .il")[currentPosition-1]).attr("tm").split("-")[0]
if (recent_action=="interval_clicked") aud.currentTime = cur_time; 
recent_action = "play_button";
play_mode="stream";
aud.play();	
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);

}

function repeatControl_clicked(){
if(currentPosition == 0) currentPosition = 1;
recent_action = "repeat_button";
play_mode="phrase";
play_interval(jQuery(jQuery(chapter_id+" .il")[currentPosition-1]).attr("tm"));	
show_in_player();
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);
}

function backControl_clicked(){
recent_action = "back_button";
play_mode="phrase";
currentPosition--;
if_chapter_start_open_prev();
play_interval(jQuery(jQuery(chapter_id+" .il")[currentPosition-1]).attr("tm"));	
show_in_player();
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);
}

function forwardControl_clicked(){
recent_action = "forward_button";
play_mode="phrase";
currentPosition++;
if (currentPosition <= $(".il").length) { 
play_interval(jQuery(jQuery(chapter_id+" .il")[currentPosition-1]).attr("tm"));	
show_in_player();
}
else open_chapter(next_chapter_id (),1);
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);
}

function pauseControl_clicked(){
recent_action = "pause_button";
aud.pause();	
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);
}

function dictantControl_clicked() {
if(typeof dictantTimer != "undefined")clearInterval(dictantTimer);
play_mode = "stream";
if(currentPosition == 0) currentPosition = 1;
dictantPlay(currentPosition,0);
}

function dictantSettings_clicked() {
jQuery("#dictant_delay").val(dictant_delay);
jQuery("#dictant_repeats").val(dictant_repeats);
jQuery("#dictant-settings").toggle();
}

function set_cur_pos_clicked() {
currentPosition = parseFloat(jQuery(".set_cur_pos").index(this))+1;
show_in_player();
setTimeout(function() {recent_action = "set_cur_pos";}, 100);
}

function dictantPlay(s,x) {
//s - start position, x - delay

if (s==jQuery(chapter_id+" .il").length) return;

dictantTimer = setTimeout(function(){
dictant_cur_repeat ++;

play_interval(jQuery(jQuery(chapter_id+" .il")[s-1]).attr("tm"));
var t = jQuery(jQuery(chapter_id+" .il")[s-1]).attr("tm").split("-");
x = Math.round((parseFloat(t[1])-parseFloat(t[0]))*1000*dictant_delay);
show_in_player();
if(dictant_cur_repeat<dictant_repeats) {dictantPlay(s,x); currentPosition = s;}
else {dictantPlay(s+1,x); dictant_cur_repeat=0;currentPosition = s+1;}

	}, x);
}

function dictant_settings_change() {
dictant_delay = parseFloat(jQuery("#dictant_delay").val().trim());
dictant_repeats = parseFloat(jQuery("#dictant_repeats").val().trim());
}

function player_timeupdate() 		{ 	
		if(aud.currentTime > 0){
		jQuery("#playControl").hide();
		jQuery("#pauseControl").show();
		//jQuery("#pauseControl, #playControl").css({display: "inline-block"});
		}
		if(play_mode=="stream"){
		
		//console.log(aud.currentTime);
		if((currentPosition == 0)&&(aud.currentTime > 0)) currentPosition = 1;
				show_in_player();
		
		if ((parseFloat(aud.currentTime)>jQuery(jQuery(chapter_id+" .il")[currentPosition-1]).attr("tm").split("-")[1])) {
				show_in_player();
				currentPosition ++;
			}}
		}

function audio_paused() 		{		
	jQuery("#playControl").show();
	jQuery("#pauseControl").hide();
	//jQuery("#pauseControl, #playControl").css({display: "inline-block"});
	}
		
function audio_end() {
if(play_mode == "stream"){
open_chapter(next_chapter_id (),1);
setTimeout(aud.play(),4000);
$("#playControl").hide();
$("#pauseControl").show();
}
}
		
function add_player_events() {
	chapter_id = "";
	//currentPosition = 1;
	jQuery('.chapter, .words, .dialog').prepend(player);
	aud = jQuery('audio')[0];
	aud.addEventListener('timeupdate', player_timeupdate , false);
	aud.addEventListener('pause', audio_paused , false);

	aud.addEventListener('ended', audio_end , false);
	jQuery('#playControl').click(playControl_clicked); 
	jQuery('#pauseControl').click(pauseControl_clicked); 
	jQuery('#forwardControl').click(forwardControl_clicked); 
	jQuery('#backControl').click(backControl_clicked); 
	jQuery('#repeatControl').click(repeatControl_clicked); 
	jQuery('#dictantControl').click(dictantControl_clicked); 
	jQuery('#dictantSettings').click(dictantSettings_clicked); 
	jQuery('#dictant-settings-change').click(dictant_settings_change);
	jQuery("#pauseControl").hide();
	jQuery('.il').click(interval_clicked);
	jQuery(".set_cur_pos").click(set_cur_pos_clicked);

	}

function show_in_player() {
jQuery('#cur-pos-block').html((currentPosition) +"/"+jQuery(" .il").length);
jQuery('#slideshow-block').html(jQuery(" .il .ph-or")[currentPosition-1].outerHTML+jQuery(" .il .ph-tr")[currentPosition-1].outerHTML);
jQuery(".set_cur_pos").removeClass("active");
jQuery(jQuery(".set_cur_pos")[currentPosition-1]).addClass("active");
}

	
// PLAYER functions >

// < MENU
function add_menu_events(){
	jQuery(".menu-subchapter").hide();
	jQuery(".menu-chapter").click(function () {
	jQuery(this).next().toggle("slow");
	jQuery(this).toggleClass("plus");
	jQuery(this).toggleClass("minus");
});
	jQuery("#open-close-all").click(function () {
	jQuery(".menu-subchapter").toggle("slow");
	jQuery(this).toggleClass("plus");
	jQuery(this).toggleClass("minus");
	jQuery(".menu-chapter").toggleClass("plus");
	jQuery(".menu-chapter").toggleClass("minus");
});
	jQuery('.menu-subchapter li, .menu.subchapters li').click(menu_chapter_clicked);
}

function menu_chapter_clicked() {
open_chapter($(this).attr("id"),0);
return false;
}

function open_chapter(id,curPos) {
currentPosition = curPos;
jQuery(".current-chapter").html("");

if(jQuery(".book-content").length > 0) generate_html_from_content(id, ".current-chapter" );
else 
	if(jQuery("#source").length > 0 ) generate_html_from_source(id, ".current-chapter" );
	
jQuery(".current-chapter").prepend('<div id="current-chapter-name"></div>');

jQuery("#current-chapter-name").html("<center><h1>"+jQuery("li#"+id).text()+"</h1></center>");	
}

function generate_menu(target) {


		$(target).append('<ul class="menu"></ul>');
		
		
		var template_menu_chapter = '<li title="{tr_chapter_name}"  class="menu-chapter plus" >{or_chapter_name}</li><ul class="menu-subchapter" id="sm{chapter_id}"></ul>';
		
		var template_menu_subchapter = '<li id="{sub_chapter_id0}"><a href="/{sub_chapter_id}">{sub_chapter_name}</a></li>';
		
	
		var menu_content = '';
		var or_chapter_names = $("#original-chapters-names").text().trim().split("\n");
		var tr_chapter_names = $("#translation-chapters-names").text().trim().split("\n");
		var sub_chapter_names = $("#translation-subchapters-names").text().trim().split("\n");

		// если есть главы и подглавы - делаем раскрывающееся меню
		if( or_chapter_names.length>1 || tr_chapter_names.length>1){
		$("ul.menu").append('<li id="open-close-all" title="развернуть/свернуть всё" class="plus"></li>');
				
				$(or_chapter_names).each(function(c,elem) {
					menu_content += template_menu_chapter.supplant({chapter_id:(c+1),tr_chapter_name:tr_chapter_names[c],or_chapter_name:or_chapter_names[c]});
				});
				
				$("ul.menu").append(menu_content);
				
				$(sub_chapter_names).each(function(c,elem) {
				var sub_chapter_array = elem.split('.');
				var sub_chapter_id = sub_chapter_array[0]+"-"+sub_chapter_array[1];
				var sub_chapter_id0 = sub_chapter_array[0]+"_"+sub_chapter_array[1];
					$("#sm"+sub_chapter_array[0]).append(template_menu_subchapter.supplant({sub_chapter_id0:sub_chapter_id0,sub_chapter_id:sub_chapter_id, sub_chapter_name: elem}));
				
				});
		
		}
		
		else {
		
				$(sub_chapter_names).each(function(c,elem) {
				var sub_chapter_array = elem.split('.');
				var sub_chapter_id = sub_chapter_array.length < 3 ? sub_chapter_array[0] : sub_chapter_array[0]+"_"+sub_chapter_array[1];
				$("ul.menu").append(template_menu_subchapter.supplant({sub_chapter_id0:sub_chapter_id,sub_chapter_id:sub_chapter_id, sub_chapter_name: elem}));
				
				});
				$("ul.menu").addClass("subchapters");
		}
		
		add_menu_events();
}
// MENU >

function add_blank_book_html() {
jQuery("body").append('<div id="left-sidebar"><div id="book-name"><img src="images/logo.png" width="243px" align="center"></div><div id="menu"></div></div><div class="chapter current-chapter"></div>');}


function if_chapter_start_open_prev() {
 
if (currentPosition < 1) { 
open_chapter(prev_chapter_id (),0);
currentPosition = jQuery(".il").length+1;
}
}

function next_chapter_id () {
var id = $("#co"+$(".current-chapter").attr("id")+".chapter-content").next().attr("id")||$("#ti"+$(".current-chapter").attr("id")).next().attr("id");
return id.substring(2);
}

function prev_chapter_id () {
var id = $("#co"+$(".current-chapter").attr("id")+".chapter-content").prev().attr("id")||$("#ti"+$(".current-chapter").attr("id")).prev().attr("id");
return id.substring(2);
}