var SEGMENT_START = 0;
var SEGMENT_LENGTH = 1;
var SEGMENT_FILENAME = 2;

var glFileExtension = 'wav';
var glRunning = 0;
var glIsSegmented = 0;

var glSegmentIndex = 0;
var glSegmentLength = 60;
var glRecordingLength = 0;

var glAudioFilePosition = 0;

// zoznam elementov, ktorych sa tyka zvyraznovanie prave prehravaneho bodu / prispevku
var glPoaElements = [];
var glSpeechElements = [];

// Load method - init method
function onLoad()
{
    TranslateControls();

    // Load values
    try
    {
        eval('glSegmentLength = rd_GetSegmentLength(); glRecordingLength = rd_GetRecordingLength();');
    }
    catch (e)
    {
        // alert("LOAD Error:" + e)
        if (window.console && console.error("Error:" + e));
    }
    // get audio element
    if (window.HTMLAudioElement)
    {
        try
        {
            var audio = document.getElementById("mp3_audio_player");

            audio.addEventListener('error', myAudioErrorHandler, false);
            audio.addEventListener('ended', myAudioEndedHandler, false);
            audio.addEventListener('canplay', myAudioCanPlayHandler, false);
            audio.addEventListener('timeupdate', myAudioTimeUpdateHandler, false);
			audio.addEventListener('pause', myAudioPauseHandler, false);
			audio.addEventListener('play', myAudioPlayHandler, false);

            // uncomment line below to see which file from fallback browser loded by default
            //alert(audio.currentSrc);
			glFileExtension = audio.currentSrc.split('.').pop();

			if (audio.currentSrc.indexOf("recording.") > -1)
            {
                glIsSegmented = 0;
                audio.load();
            }
            else
            {
                glIsSegmented = 1;
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("LOAD - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
	
    doRefreshControls();
	
	// vytvorime zoznamy pre aktualizaciu prave prehravanych bodov
	try 
	{
		// vyhladame elementy podla prideleneho ID
		var all = document.getElementsByTagName("input");
		for (var i=0, max=all.length; i < max; i++) 
		{
			var currentElement = all[i];
			var elemId = currentElement.id;
			
			if (elemId.startsWith('BTPD')) 
			{
				var st = parseInt(elemId.substr(4));

				if (!isNaN(st))
				{
					glSpeechElements.push({start: st, end: glRecordingLength, id: elemId, element: currentElement});
				}				
			}
			else if (elemId.startsWith('BTP'))
			{
				var st = parseInt(elemId.substr(3));

				if (!isNaN(st))
				{
					glPoaElements.push({start: st, end: glRecordingLength, id: elemId, element: currentElement});
				}
			}
		}
		
		// zotriedime body
		glPoaElements.sort(function(a,b){return a.start - b.start;});

		// koniec predchadzajuceho sa rovna zaciatok nasledujuceho
		for (var i=0, max=glPoaElements.length - 1; i < max; i++) 
		{
			glPoaElements[i].end = glPoaElements[i + 1].start;
		}

		// zotriedime diskusne prispevky
		glSpeechElements.sort(function(a,b){return a.start - b.start;});

		// koniec predchadzajuceho sa rovna zaciatok nasledujuceho
		for (var i=0, max=glSpeechElements.length - 1; i < max; i++) 
		{
			glSpeechElements[i].end = glSpeechElements[i + 1].start;
		}
	}
	catch (e)
	{
		// Fail silently but show in F12 developer tools console
		if (window.console && console.error("Error:" + e));
	}
}

// Fires when the current playlist is ended
function myAudioEndedHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }
            // What you want to do after the event
            var audio = document.getElementById("mp3_audio_player");

            if (glRunning == 1)
            {
                if (glIsSegmented == 1 && glSegmentIndex < glSegmentLength.length - 1)
                {
                    doPlayNextSegment();
                }
            }
            // last file ended
            if (glSegmentIndex == glSegmentLength.length - 1)
            {
                glRunning = 0;
                audio.pause();
				doRefreshControls();
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("END - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

// 	Fires when an error occurred during the loading of an audio
function myAudioErrorHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }
            // What you want to do after the event
            var aLanguageControl = document.getElementById("page_language");

            switch (aLanguageControl.innerHTML)
            {
                case "EN":
                    alert("Your browser does not support created audio format!");
                    break;
                case "CZ":
                    alert("Váš prohlížeč nepodporuje vytvořen zvukový formát!");
                    break;
                case "PL":
                    alert("Twoja przeglądarka nie obsługuje formatu dźwięku stworzył!");
                    break;
                default:
                    alert("Váš prehliadač nepodporuje vytvorený zvukový formát!");
                    break;
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("ERROR - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

// Fires when the browser can start playing the audio
function myAudioCanPlayHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }

            // What you want to do after the event
            var audio = document.getElementById("mp3_audio_player");

            if (glAudioFilePosition != 0 && glIsSegmented == 1)
            {
                if (glAudioFilePosition > audio.duration)
                {
                    audio.currentTime = audio.duration;
                }
                else
                {
                    audio.currentTime = glAudioFilePosition;
                }

                glAudioFilePosition = 0;
            }

			if (glRunning)
			{
				if (audio.paused)
				{
					audio.play();
				}
			}
            // alert('CAN PLAY - Source = ' + audio.currentSrc + ' Duration = ' + audio.duration);
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("CAN PLAY - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

// Fires when the browser has loaded meta data for the audio
function myAudioTimeUpdateHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }
            var audio = document.getElementById("mp3_audio_player");
			var aLabelTime = document.getElementById("lblTime");
			
            // alert('TIME UPDATE - Source = ' + audio.currentSrc + ' Duration = ' + audio.duration);
            var cas;
            var wstr;

            if (glIsSegmented == 1)
            {
                cas = audio.currentTime + glSegmentLength[glSegmentIndex][SEGMENT_START];
            }
            else
            {
                cas = audio.currentTime;
            }
			// Zobrazime aktualny cas
            wstr = to2CWStr(Math.floor(cas / 3600), 2) + ":" + to2CWStr(Math.floor(cas / 60) % 60) + ":" + to2CWStr(Math.floor(cas % 60));
            lblTime.innerHTML = wstr;

			// zvyraznime element, v ktorom sa nachadzame
			{				
				// cas zaciatku prave prehravanaho bodu
				var currentPoaStart = Number.MAX_VALUE;

				// najdeme prehravany bod a zvyraznime. Ostatne su nevyrazne.
				for (var i=0, max=glPoaElements.length; i < max; i++)
				{
					var poa = glPoaElements[i];

					if (cas > poa.start && cas < poa.end)
					{
						// zvyraznime
						poa.element.className = "ButtonSymbolPlayActive";
						currentPoaStart = poa.start;
					}
					else
					{
						// standard
						poa.element.className = "ButtonSymbolPlay";
					}
				}

				// najdeme prehravany prispevok a zvyraznime. Ostatne su nevyrazne.
				for (var i=0, max=glSpeechElements.length; i < max; i++)
				{
					var speech = glSpeechElements[i];
					speech.element.className = 
						(cas > speech.start && cas < speech.end && speech.start > currentPoaStart)
						? "ButtonSymbolPlayActive"
						: "ButtonSymbolPlay";
				}
			}
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("TIMEUPDATE - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

// Fires when the audio has been paused
function myAudioPauseHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }
			
            //var audio = document.getElementById("mp3_audio_player");
			doRefreshControls();
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("PAUSE - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

// Fires when the audio has been started or is no longer paused
function myAudioPlayHandler(e)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            if (!e)
            {
                e = window.event;
            }
			
            //var audio = document.getElementById("mp3_audio_player");
			doRefreshControls();
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            // alert("PLAY - Error:" + e);
            if (window.console && console.error("Error:" + e));
        }
    }
}

//----- Naviazeme na prehravanie spustenim dalsieho segmentu
function doPlayNextSegment()
{
    if (glIsSegmented == 1)  // je splitnute podla bodov
    {
        // ak je nahravanie spustene a nie sme za poslednym segmentom
        if (glRunning)
        {
            glSegmentIndex++;
            if (glSegmentIndex < glSegmentLength.length)
            {
                // Mame dalsi segment - prehrame ho	
                doStart(glSegmentLength[glSegmentIndex][SEGMENT_START]);
            }
            else
            {
                // Prehravanie skoncilo na konci suboru
                glRunning = 0;
            }
        }
        else
        {
            // Obsluha ukocila prehravanie
            doRefreshControls();
        }
    }
    else
    {
        // nesegmentovany subor
        doRefreshControls();
    }
}

//----- Spustanie a zastavovanie nahravania od poslednej pozicie
function doPause()
{
    if (window.HTMLAudioElement)
    {
        try
        {
            var audio = document.getElementById("mp3_audio_player");
			
            if (audio.paused)
            {
				glRunning = 1;
				audio.play();
            }
            else
            {
				glRunning = 0;
				audio.pause();
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            if (window.console && console.error("Error:" + e));
        }
    }
}

//----- Posunutie miesta z akt. pozicie
function doStartRelative(step)
{
    if (window.HTMLAudioElement)
    {
        try
        {
            var audio = document.getElementById("mp3_audio_player");
			var aTime = audio.currentTime + step;

            if (glIsSegmented == 1)
            {
                aTime += glSegmentLength[glSegmentIndex][SEGMENT_START];
            }
			
			doStart(aTime);
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            if (window.console && console.error("Error:" + e));
        }
    }
}

// Nastavi segment ktory obsahuje cas kde je pozadovane skocit
function setNearesetSegment(theTime)
{
    for (i = 0; i < glSegmentLength.length; ++i)
    {
        if (theTime >= glSegmentLength[i][SEGMENT_START])
        {
            glSegmentIndex = i;
            continue;
        }
        else
        {
            break;
        }
    }
}

// moves to the end of recording
function doEnd()
{
    try
        {
            var audio = document.getElementById("mp3_audio_player");

            if (glIsSegmented == 1)
            {
                glSegmentIndex = glSegmentLength.length - 1;
                var fn = './sound/' + glSegmentLength[glSegmentIndex][SEGMENT_FILENAME] + '.' + glFileExtension;

                glAudioFilePosition = glSegmentLength[glSegmentIndex][SEGMENT_LENGTH];

                audio.setAttribute("src", fn);
                audio.load();
            }
            else
            {
                audio.currentTime = audio.duration;
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            if (window.console && console.error("Error:" + e));
        }
}


//----- Spustime prehravanie od zadaneho casu
function doStart(fromS)
{
    // alert(fromS);
    if (window.HTMLAudioElement)
    {
        try
        {
            var audio = document.getElementById("mp3_audio_player");
			glRunning = 1;
		
            if (glIsSegmented == 1)
            {
                setNearesetSegment(fromS);

                var fn = './sound/' + glSegmentLength[glSegmentIndex][SEGMENT_FILENAME] + '.' + glFileExtension;
                glAudioFilePosition = fromS - glSegmentLength[glSegmentIndex][SEGMENT_START];

                audio.setAttribute("src", fn);
                audio.load();
            }
            else
            {
                // Nesegmentovany subor
				if (fromS < 0)
				{
					audio.currentTime = 0;
				}
				else if (fromS > audio.duration)
                {
                    audio.currentTime = audio.duration;
                }
				else
				{
					audio.currentTime = fromS;
				}

				if (audio.paused)
				{
					// Zacneme hrat
					audio.play();
                }
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            if (window.console && console.error("Error:" + e));
        }
    }
}

//----- Trocha formatovania
function to2CWStr(i)
{
    var s = '000' + i.toString();
    return s.substr(s.length - 2, 2);
}

//----- Aktualizujeme zobrazenie kontrolneho panela
function doRefreshControls()
{
    if (window.HTMLAudioElement)
    {
        try {
            var audio = document.getElementById("mp3_audio_player");
            var btnPause = document.getElementById("btnPause");
            var lblStatus = document.getElementById("lblStatus");
            var aLanguageControl = document.getElementById("page_language");

            if (audio.paused)
            {
                // Sme zastaveny
                btnPause.style.backgroundImage = "url('./img/play_continue.png')";

                switch (aLanguageControl.innerHTML)
                {
                    case "EN":
                        lblStatus.innerHTML = "Playback stopped";
                        break;
                    case "PL":
                        lblStatus.innerHTML = "Odtwarzanie zatrzymane";
                        break;
                    case "CZ":
                        lblStatus.innerHTML = "Přehrávání zastaveno";
                        break;
                    default:
                        lblStatus.innerHTML = "Prehrávanie zastavené";
                        break;
                }
            }
            else
            {
                //Bezime
                btnPause.style.backgroundImage = "url('./img/play_pause.png')";

                switch (aLanguageControl.innerHTML)
                {
                    case "EN":
                        lblStatus.innerHTML = "Playback started";
                        break;
                    case "PL":
                        lblStatus.innerHTML = "Odtwarzanie rozpoczęte";
                        break;
                    case "CZ":
                        lblStatus.innerHTML = "Přehrávání spuštěno";
                        break;
                    default:
                        lblStatus.innerHTML = "Prehrávanie spustené";
                        break;
                }
            }
        }
        catch (e)
        {
            // Fail silently but show in F12 developer tools console
            if (window.console && console.error("Error:" + e));
        }
    }
}

// handles button + or - for showing recording details
function showDetails(id)
{
    var buttonExpand = document.getElementById("BTE" + id);
    var spanObject = document.getElementById("SP" + id);

    if (buttonExpand.className == "ButtonSymbolPlus")
    {
        // Expand
        buttonExpand.className = "ButtonSymbolMinus";
        spanObject.className = "SpanVisible";
    }
    else
    {
        // Collapse
        buttonExpand.className = "ButtonSymbolPlus";
        spanObject.className = "SpanHidden";
    }
    return;
}

// translates titles of controls to webpage language
function TranslateControls()
{
    var aLanguageControl = document.getElementById("page_language");

    var aButtonPlayStart = document.getElementById("buttonPlayStart");
    var aButtonPlayb3 = document.getElementById("buttonPlayb3");
    var aButtonPlayb2 = document.getElementById("buttonPlayb2");
    var aButtonPlayb1 = document.getElementById("buttonPlayb1");
    var aButtonPause = document.getElementById("btnPause");
    var aButtonPlay1 = document.getElementById("buttonPlay1");
    var aButtonPlay2 = document.getElementById("buttonPlay2");
    var aButtonPlay3 = document.getElementById("buttonPlay3");
    var aButtonPlayEnd = document.getElementById("buttonPlayEnd");
    var aLabelTime = document.getElementById("lblTime");
    var aLabelStatus = document.getElementById("lblStatus");

    var session_date_label = document.getElementById("session_date_label");
    var session_chairman_label = document.getElementById("session_chairman_label");

    switch (aLanguageControl.innerHTML)
    {
        case "EN":
            aButtonPlayStart.setAttribute("Title", "Play from the beginning.");
            aButtonPlayb3.setAttribute("Title", "Rewind 60 seconds and play.");
            aButtonPlayb2.setAttribute("Title", "Rewind 16 seconds and play.");
            aButtonPlayb1.setAttribute("Title", "Rewind 4 seconds and play.");
            aButtonPause.setAttribute("Title", "Play from the beginning.");
            aButtonPlay1.setAttribute("Title", "Forward 4 seconds and play.");
            aButtonPlay2.setAttribute("Title", "Forward 16 seconds and play.");
            aButtonPlay3.setAttribute("Title", "Forward 60 seconds and play.");
            aButtonPlayEnd.setAttribute("Title", "Jump to the end.");
            aLabelTime.setAttribute("Title", "Current position.");
            aLabelStatus.setAttribute("Title", "Recording state.");

            session_date_label.innerHTML = "Session date:";
            session_chairman_label.innerHTML = "Chairman:"
            break;
        case "CZ":
            aButtonPlayStart.setAttribute("Title", "Spuštění přehrávání od začátku záznamu.");
            aButtonPlayb3.setAttribute("Title", "Posun o 60 sekund zpět a spuštění přehrávání.");
            aButtonPlayb3.setAttribute("Title", "Posun o 60 sekund zpět a spuštění přehrávání.");
            aButtonPlayb2.setAttribute("Title", "Posun o 16 sekund zpět a spuštění přehrávání.");
            aButtonPlayb1.setAttribute("Title", "Posun o 4 sekundy zpět a spuštění přehrávání.");
            aButtonPause.setAttribute("Title", "Spuštění přehrávání od začátku záznamu.");
            aButtonPlay1.setAttribute("Title", "Posun o 4 sekundy vpřed a spuštění přehrávání.");
            aButtonPlay2.setAttribute("Title", "Posun o 16 sekund vpřed a spuštění přehrávání.");
            aButtonPlay3.setAttribute("Title", "Posun o 60 sekund vpřed a spuštění přehrávání.");
            aButtonPlayEnd.setAttribute("Title", "Posun na konec záznamu.");
            aLabelTime.setAttribute("Title", "Aktuálni pozice (čas) v záznamu.");
            aLabelStatus.setAttribute("Title", "Stav nahrávky.");

            session_date_label.innerHTML = "Datum jednání:";
            session_chairman_label.innerHTML = "Předsedající:"
            break;
        case "PL":
            aButtonPlayStart.setAttribute("Title", "Rozpoczecie odtwarzania od początku nagrania.");
            aButtonPlayb3.setAttribute("Title", "Przesuń o 60 sekund w tył do odtworzania.");
            aButtonPlayb2.setAttribute("Title", "Przesuń o 16 sekund w tył do odtworzania.");
            aButtonPlayb1.setAttribute("Title", "Przesuń o 4 sekundy w tył do odtworzania.");
            aButtonPause.setAttribute("Title", "Rozpoczęcie odtwarzania od początku nagrywania.");
            aButtonPlay1.setAttribute("Title", "Przesuń o 4 sekundy do przodu do odtworzania.");
            aButtonPlay2.setAttribute("Title", "Przesuń o 16 sekund do przodu do odtworzania.");
            aButtonPlay3.setAttribute("Title", "Przesuń o 60 sekund do przodu do odtworzania.");
            aButtonPlayEnd.setAttribute("Title", "Przejdź do końca nagrania.");
            aLabelTime.setAttribute("Title", "Aktualna pozycja (czas) v nagraniu dźwięku.");
            aLabelStatus.setAttribute("Title", "");

            session_date_label.innerHTML = "Data sesji:";
            session_chairman_label.innerHTML = "Przewodniczący:"
            break;
        default:
            aButtonPlayStart.setAttribute("Title", "Spustenie prehrávania od začiatku záznamu.");
            aButtonPlayb3.setAttribute("Title", "Posun o 60 sekúnd naspäť a spustenie prehrávania.");
            aButtonPlayb2.setAttribute("Title", "Posun o 16 sekúnd naspäť a spustenie prehrávania.");
            aButtonPlayb1.setAttribute("Title", "Posun o 4 sekundy naspäť spustenie prehrávania.");
            aButtonPause.setAttribute("Title", "Spustenie a zastavenie prehrávania.");
            aButtonPlay1.setAttribute("Title", "Posun o 4 sekundy dopredu a spustenie prehrávania.");
            aButtonPlay2.setAttribute("Title", "Posun o 16 sekúnd dopredu a spustenie prehrávania.");
            aButtonPlay3.setAttribute("Title", "Posun o 60 sekúnd dopredu a spustenie prehrávania.");
            aButtonPlayEnd.setAttribute("Title", "Posun na koniec záznamu.");
            aLabelTime.setAttribute("Title", "Aktuálna pozícia (čas) v zázname.");
            aLabelStatus.setAttribute("Title", "Stav nahrávky.");

            session_date_label.innerHTML = "Dátum konania:";
            session_chairman_label.innerHTML = "Predsedajúci:"
            break;
    }
}
