/*
# LAST UPDATES
# 04/09/2020 V1.03 MZ added end_time parameter and autoplay when start_time is set
*/

var VERSION='1.03';

var beginVideoAt = 0;
var endVideoAt = 0;

// parse this as early as possible
var urlString = window.location.href;
var url = new URL(urlString);
var start_time = url.searchParams.get("start_time");
var end_time = url.searchParams.get("end_time");

if (start_time && start_time !== "") {
    console.log("Setting start time: " + start_time);
    beginVideoAt = start_time;
}
if (end_time && end_time !== "") {
    console.log("Setting end time: " + end_time);
    endVideoAt = end_time;
}


var lastStart = 0;
var notScrollOnSentence = -1;
var editMode = 0;
if (/(msie\ [0-9]{1})/i.test(navigator.userAgent) || /(Trident\/7\.)/i.test(navigator.userAgent)) {
    alert("WARNING: Internet Explorer is not supported. Please use Chrome or Firefox web browser");
}

function setPlaybackSpeed(speed) {
    console.log("Setting playback speed to: " + speed);
    video.playbackRate = parseFloat(speed);
}

function get(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.onload = function () {
        cb(this.responseText);
    }
    xhr.send();
}
function get_json(url, cb) {
    get(url, function (x) {
        cb(JSON.parse(x));
    });
}
function scrollToActive() {
    let activeElement = $("span.active");
    $transcript.scrollTo(activeElement, { interrupt: 'true', offset: -120, duration: 1 })
}

var sentenceHighlighted = -1;
function highlightSentence(sentenceId) {

    if (sentenceHighlighted != -1 && sentenceHighlighted != sentenceId) {
        unHighlightSentence(sentenceHighlighted);
    }
    sentenceHighlighted = sentenceId;
    const xx = document.querySelectorAll("[s='" + sentenceId + "']");
    for (var i = 0; i < xx.length; i++) {
        xx[i].classList.remove('unhl');
        xx[i].classList.add('hl');
        //xx[i].style.backgroundColor ="yellow";
        //xx[i].style.color ="black";
    }
}
function unHighlightSentence(sentenceId) {
    const xx = document.querySelectorAll("[s='" + sentenceId + "']");
    for (var i = 0; i < xx.length; i++) {
        xx[i].classList.remove('hl');
        xx[i].classList.add('unhl');
        // xx[i].style.backgroundColor ="white";
        if (TRANS[1] !== undefined && xx[i].className != "translation") {
            //BP: find a better way
            //xx[i].style.color ="white";
        }
    }
}

var $a = document.getElementById("video");
//$a.currentTime = 0.0;
console.log("Begin: " + beginVideoAt);
if (beginVideoAt && beginVideoAt > 0) {
    console.log("Starting video at " + beginVideoAt);
    $a.currentTime = beginVideoAt;
}

var scrolling = 0;
var $trans = document.getElementById("transcript");
var wds = [];
var cur_wd;
var machineScroll = false;
var $transcript = $("#transcript");

//$transcript.scroll( function(e){

//scrolling=$.now();
//} );

//$("#send").css("display","none");

var $phones = null; //document.createElement("div");
//$phones.className = "phones";
//document.body.appendChild($phones);
//$phones.scrollIntoView({ behavior:"instant", block: "center" });

var keystrokes=0;
var cur_phones$ = [];           // List of phoneme $divs
var $active_phone;
document.onkeyup = function(evt) {
    console.log("key:"+evt.keyCode);
    if (evt.keyCode == 27) {
        document.getElementById("transcript").pause();
    }
    if (evt.keyCode < 48) {
        return true;
    }
    if (editMode == 0) {
        alert("you cannot edit, first double-click");
        return false;
    }
    evt = evt || window.event;
    keystrokes++;
    $('#send').attr('value',"Save your "+keystrokes+" change"+(keystrokes>1?"s":""));
};

function render_phones(wd) {

    cur_phones$ = [];
    $phones.innerHTML = "";
    $active_phone = null;

    $phones.style.top = wd.$div.offsetTop + 28;
    $phones.style.left = wd.$div.offsetLeft;

    var dur = wd.end - wd.start;

    var start_x = wd.$div.offsetLeft;

    wd.phones
        .forEach(function (ph) {
            var $p = document.createElement("span");
            $p.className = "phone";
            $p.textContent = ph.phone.split("_")[0];
            $phones.appendChild($p);
            cur_phones$.push($p);
        });

    var offsetToCenter = (wd.$div.offsetWidth - $phones.offsetWidth) / 2;
    $phones.style.left = wd.$div.offsetLeft + offsetToCenter;
}

function highlight_phone(t) {
    if (!cur_wd) {
        $phones.innerHTML = "";
        return;
    }
    var hit;
    var cur_t = cur_wd.start;

    cur_wd.phones.forEach(function (ph, idx) {
        if (cur_t <= t && cur_t + ph.duration >= t) {
            hit = idx;
        }
        cur_t += ph.duration;
    });

    if (hit) {
        var $ph = cur_phones$[hit];
        if ($ph != $active_phone) {
            if ($active_phone) {
                $active_phone.classList.remove("phactive");
            }
            if ($ph) {
                $ph.classList.add("phactive");
            }
        }
        $active_phone = $ph;
    }
}

var lasttime = 0;

function highlight_word() {
    var t = $a.currentTime;
    if (t == undefined) { t = lasttime + 1; }
    if (t < lasttime) { lasttime = t - 1; }
    //if ($.now()-scrolling > 0) {
    if (t - lasttime > 0.001) {
        //console.log("lasttime=",t-lasttime);
        lasttime = t;
        // XXX: O(N); use binary search
        var hits = wds.filter(function (x) {
            return (t - x.start) > 0.01 && (x.end - t) > 0.01;
        }, wds);
        var next_wd = hits[hits.length - 1];

        if (cur_wd != next_wd) {
            var active = document.querySelectorAll('.active');
            for (var i = 0; i < active.length; i++) {
                active[i].classList.remove('active');
                active[i].classList.add('unhl');
                //active[i].style.backgroundColor ="white";

            }
            if (next_wd && next_wd.$div) {
                next_wd.$div.classList.add('active');

                highlightSentence(next_wd.$div.getAttribute("s"));
                //render_phones(next_wd);
                //active.scrollIntoView( {behavior:"smooth", block:"center"});
            }
        }
        cur_wd = next_wd;
        //highlight_phone(t);

        scrollToActive();
	
	    // stop playing if parameter set (from URL)
	    if (endVideoAt > 0 && endVideoAt < t) {
            $a.pause();
            endVideoAt = 0;
        }

	    window.requestAnimationFrame(highlight_word);
    } else {
        //scrollToActive();
        //console.log("wait"+(t-lasttime));

        window.requestAnimationFrame(highlight_word);
    }

}

// MZ 2019-10-16
//window.requestAnimationFrame(highlight_word);

// MZ 2019-10-16
//$trans.innerHTML = "Loading...";


function render(ret) {
    wds = ret['words'] || [];
    transcript = ret['transcript'];

    $trans.innerHTML = '';


    var currentOffset = 0;
    var s = 0;
    var previousStart = -1;
    var $sentence = document.createElement("div");
    $sentence.setAttribute("s", s);
    $sentence.className = "original";
    $sentence.id = docid + '_' + s;
    wds.forEach(function (wd) {
        if (wd.case == 'not-found-in-transcript') {
            // TODO: show phonemes somewhere
            var txt = ' ' + wd.word;

            var $wd = document.createElement('span');
            $wd.className = 'nonsuccess';
            var $wdText = document.createTextNode(txt);
            $wd.appendChild($wdText);
            $wd.setAttribute("s", s + 1);

            $sentence.appendChild($wd);

            //var $plaintext = document.createTextNode(txt);
            //$sentence.appendChild($plaintext);

            return;
        }
        // Add non-linked text
        if (wd.startOffset > currentOffset) {
            var txt = transcript.slice(currentOffset, wd.startOffset);
            //if (txt != ' ') {txt = txt+' ';}
            var idxcr = txt.indexOf('\n'); var rest = "";
            if (idxcr > - 1) { rest = txt.substring(idxcr + 1); txt = txt.substring(0, idxcr); }

            var $plaintext = document.createTextNode(txt);
            //$trans.appendChild($plaintext);
            $sentence.appendChild($plaintext);
            if (idxcr > -1) {
                $trans.appendChild($sentence);
                $sentence = document.createElement("div");
                if (rest != "") { $sentence.appendChild(document.createTextNode(rest)); }
                var $translation = document.createElement('div');

                var newStart = previousStart;
                if (wd.start !== undefined && wd.start > previousStart) {
                    newStart = wd.start;
                }
                var translated = TRANS[s++];
                $sentence.setAttribute("s", s + 1);
                $sentence.className = "original";
                $sentence.id = docid + '_' + (s + 1);
                if (translated !== undefined) {
                    $plaintext = document.createTextNode(translated + "\n");
                    $translation.appendChild($plaintext);
                    $translation.className = "translation";
                    $translation.setAttribute("s", s);
                    //change direction is current doc is in Arabic language
                    if ($(location).attr('href').match(/_tr_ar/)) { $translation.setAttribute("dir", "rtl"); }
                }
                wd.previousStart = previousStart;
                $translation.onclick = function () {
                    console.log("wd" + wd.start + " previous:" + wd.previousStart);
                    if (wd.previousStart > wd.start) {
                        $a.currentTime = wd.start;
                    } else {
                        $a.currentTime = wd.previousStart;
                    }
                    lastStart = wd.s;
                    $a.play();
                };
                wd.s = s;
                $translation.onmouseover = function () {
                    console.log("hl:" + wd.s);
                    highlightSentence(wd.s);
                };
                $trans.appendChild($translation);
                previousStart = newStart;
            }
            currentOffset = wd.startOffset;
        }
        var $wd = document.createElement('span');
        var txt = transcript.slice(wd.startOffset, wd.endOffset);
        var $wdText = document.createTextNode(txt);
        $wd.appendChild($wdText);
        $wd.setAttribute("s", s + 1);
        $sentence.appendChild($wd);
        //if (TRANS !== undefined && TRANS[1] !== undefined) {
        // MZ commented out and setting in CSS now
        //$wd.style.color='white';
        //}
        wd.$div = $wd; wd.s = s;
        if (wd.start !== undefined) {
            $wd.className = 'success';
        }
        $wd.onclick = function () {
            if (wd.start !== undefined && notScrollOnSentence != wd.s) {
                lastStart = wd.s;
                console.log(wd.start);
                $a.currentTime = wd.start;
                $a.play();
            }
        };
        $wd.DISABLEDondblclick = function () {
            if (editMode == 0) {
                console.log("try jsonp:/S2T/editFile/s2tOk.jsp?id=" + docid);
		$.getJSON("/S2T/editFile/s2tOk.jsp?id=" + docid + "&canedit=1",
			  function () { console.log("Load was performed."); editMode = 1; }
			  )
		.fail(function (err) { alert("YOU CANNOT EDIT on this server, sorry"); console.log("error details = ", err); editMode = 0; })
		.done(
		      function () {
			  console.log("You can now edit text.. DO NOT FORGET to click on <send> button at the bottom of the page");
			  editMode = 1;
			  $("#send").css("display", "block");
			  $("#transcript").css("text-shadow", "1px 1px 2px lightblue");
		      });
            }

            notScrollOnSentence = wd.s;
            document.getElementById("video").pause();
          };
          // test similar behaviour on right click (for small devices?)
          $wd.DISABLEDoncontextmenu = function () {
            if (editMode == 0) {
                console.log("contextmenu-try jsonp:/S2T/editFile/s2tOk.jsp?id=" + docid);

                $.getJSON("/S2T/editFile/s2tOk.jsp?id=" + docid + "&canedit=1",
                    function () { console.log("Load was performed."); editMode = 1; }
                )
                    .fail(function (err) { alert("YOU CANNOT EDIT on this server, sorry"); console.log("error details = ", err); editMode = 0; })
                    .done(
                        function () {
                            console.log("You can now edit text.. DO NOT FORGET to click on <send> button at the bottom of the page");
                            editMode = 1;
                            $("#send").css("display", "block");
                            $("#transcript").css("text-shadow", "1px 1px 2px lightblue");
                        });
            }
            notScrollOnSentence = wd.s;
            document.getElementById("video").pause();
	    };

        //$trans.appendChild($wd);
        currentOffset = wd.endOffset;
	});

    var txt = transcript.slice(currentOffset, transcript.length);

    var $plaintext = document.createTextNode(txt);
    $sentence.appendChild($plaintext);
    $trans.appendChild($sentence);


    // add missing last translation, as current mechanism will skip / miss that (based on end of line character)
	
    var $translation = document.createElement('div');
    var translated = TRANS[s++];
    if (translated !== undefined) {
        $plaintext = document.createTextNode(translated + "\n");
        $translation.appendChild($plaintext);
        $translation.className = "translation";
        $translation.setAttribute("s", s);
        //change direction is current doc is in Arabic language
        if ($(location).attr('href').match(/_tr_ar/)) { $translation.setAttribute("dir", "rtl"); }
     }

     $translation.onclick = function () {
                    console.log("wd" + wd.start + " previous:" + wd.previousStart);
                    if (wd.previousStart > wd.start) {
                        $a.currentTime = wd.start;
                    } else {
                        $a.currentTime = wd.previousStart;
                    }
                    lastStart = wd.s;
                    $a.play();
      };
      $translation.onmouseover = function () {
         //console.log("hl:" + wd.s);
         highlightSentence(s);
      };
      $trans.appendChild($translation);


    currentOffset = transcript.length;
}

var status_init = false;
var status_log = [];
var $status_pro;




// THIS IS A DUPLICATION FROM THE DISABLED CODE that was previously bound to individual tokens for double-click
function startPostEditing() {
    if (editMode == 0) {
        console.log("try jsonp:/S2T/editFile/s2tOk.jsp?id=" + docid);

        $.getJSON("/S2T/editFile/s2tOk.jsp?id=" + docid + "&canedit=1",
            function () { console.log("Load was performed."); editMode = 1; }
        )
        .fail(function (err) { alert("YOU CANNOT EDIT on this server, sorry"); console.log("error details = ", err); editMode = 0; })
        .done(function ( editJson ) {
		     
		    console.log ("Json:" + editJson.versions);
		    if (editJson.hasOwnProperty("versions") 
			&& ( editJson.versions[ 0 ] )) {
			alert( "YOU CANNOT EDIT, as this video is already under post-edition : see " + editJson.versions[ 0 ] ); 
			
		    } else {
                // TBD: load INLINE_JSON again from server to make sure most recent version is used
                console.log("Going into edit mode...");
                dataLocation = window.location.href.replace(".html", ".json");
                console.log("Going to load data from " + dataLocation);
                //$.getJSON(dataLocation, function (data) {
			    $.ajax({dataType:"json", url:dataLocation, cache: false, 
				success: function (data) {
				    console.log("received new JSON data");
				    INLINE_JSON = data;
				    console.log("INLINE_JSON reload complete");
	                init();
        	        console.log("Init complete");
                    update();
                    console.log("Update complete");
                    console.log("You can now edit text.. DO NOT FORGET to click on <send> button at the bottom of the page"); 
                    editMode = 1;
                    $("#send").css("display", "block");
        	        $("#transcript").css("text-shadow", "1px 1px 2px lightblue");
	                alert("You are now in post-edit mode\nDo not forget to \"Save\" your document every now and then");
				}

			    });	
		    }
        });
    }
    //notScrollOnSentence = wd.s;
    document.getElementById("video").pause();
}

function update() {
    console.log("Called update ffunction");
    if (INLINE_JSON) {
        // We want this to work from file:/// domains, so we provide a
        // mechanism for inlining the alignment data.
        render(INLINE_JSON);
    }

}

function init() {

    // check if we need to jump to specific location
    //var urlString = window.location.href;
    //var url = new URL(urlString);
    //var start_time = url.searchParams.get("start_time");

    //if (start_time && start_time !== "") {
    //	beginVideoAt = start_time;
    //}

    if (typeof S2T_DISCLAIMER !== 'undefined') {
        $("#s2tdisclaimer").html(S2T_DISCLAIMER);
        $(".s2tdisclaimer").each(function() { $(this).html(S2T_DISCLAIMER); });
    }

    
    if (typeof S2T_TR_DISCLAIMER !== 'undefined' && isPageTranslation() ) {
        $("#s2tdisclaimer").html(S2T_TR_DISCLAIMER);
        $(".s2tdisclaimer").each(function() { $(this).html(S2T_TR_DISCLAIMER); });
    }


    if (typeof S2T_POWEREDBY !== 'undefined') {
        $("#s2tpoweredby").html(S2T_POWEREDBY);
        $(".s2tpoweredby").each(function() { $(this).html(S2T_POWEREDBY); });
    }

    $a = document.getElementById("video");
    $a.currentTime = 0.0;
    if (beginVideoAt && beginVideoAt > 0) {
        console.log("Setting start time at init: " + beginVideoAt);
        $a.currentTime = beginVideoAt;
    }

    $trans = document.getElementById("transcript");
    $transcript = $("#transcript");

    $transcript.scroll(function (e) {
        scrolling = $.now();
    });

    $("#send").css("display", "none");

    $phones = document.createElement("div");
    $phones.className = "phones";
    document.body.appendChild($phones);
    $phones.scrollIntoView({ behavior: "instant", block: "center" });

    window.requestAnimationFrame(highlight_word);

    if (beginVideoAt && beginVideoAt > 0) {
        var video=document.getElementById("video") ;
	    $a.play();
    }
    

     loadScript("subtitles.js", function(){ }); 
}


function loadScript(url, callback){

    var script = document.createElement("script")
    script.type = "text/javascript";

    if (script.readyState){  //IE
        script.onreadystatechange = function(){
            if (script.readyState == "loaded" ||
                    script.readyState == "complete"){
                script.onreadystatechange = null;
                callback();
            }
        };
    } else {  //Others
        script.onload = function(){
            callback();
        };
    }

    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
}

