
// add speaker HTML element

// <input class="segmentationButton" type="button" name="speakers" value="speakers" onclick='$(".segmentation").show(); $(".segmentation2").show(); $(".segmentationList1").show(); $(".segmentationList2").show();'></input>
buttonElement = $('<input  class="segmentationButton" type="button" name="speakers" value="speakers" ></input>');
buttonElement.click(function() { $(".segmentation").show(); $(".segmentationList1").show();  $(".segmentation2").show();   });

//console.log("Inserting button");
//console.log(buttonElement);
//console.log($("#video").next());

$("#video").next().append(buttonElement);


timelineElement = $('<div class="segmentationList1" id="markerDisplay" ><h3>Timeline</h3><ol id="markersList"></ol></div>');
$("body").append(timelineElement)


function jumpToTimestamp(timestamp) { $a.currentTime = timestamp; $a.play(); }


function parseSpeakers(obj, targetElementId, segmentationId, lastPosition2) {

                 	//console.log("Object:");
			//console.log(markersList);
                        //console.log(obj);
                        var markersList = $("#" + targetElementId);
			//var markersList = document.getElementById(targetElementId);

                        // lookup s-id from wds variable to later annotate speaker changes
                        var sentenceId = 0;
                        var oldSentenceId = -1;
                        var i;
			//console.log("Global: " + globalLastPosition);
			if(globalLastPosition > 0) { lastPosition2 = globalLastPosition; }

                        //console.log("Obj seconds" + obj.timestampSeconds + "   last Position: " +lastPosition2);
                        for (i=lastPosition2; i < wds.length; i++) {
                                //console.log(i + " " + wds[i].start);
                                // for debugging...
                                //if (i > 3000) {
                                //      break;
                                //}

                                if (lastPosition2 > i ) {
                                        continue;
                                }
                                lastPosition2 = i;
				globalLastPosition = i;

                                if (wds[i].start == null) {
                                        //console.log("WARNING - undefined value! " + i);
                                        continue;
                                }
                                if (wds[i].start < obj.timestampSeconds) {
                                        continue;
                                }

                                sentenceId = wds[i].s;
                                //console.log("WDS start: " + sentenceId);
                                if (oldSentenceId < sentenceId) {
                                        //console.log("Breaking...");
					console.log("Breaking at " + i );
                                        break;
                                }
                                oldSentenceId = sentenceId;
                        }
                        //console.log("---");
                        markersList.append('<li title="('+ obj.timestamp + ')" wdsid="' +i+ '" ' + 's="' + sentenceId + '" onclick="jumpToTimestamp(' + obj.timestampSeconds  + ')">' +  obj.description + '</li>');

                var newDelimiter = $('<div class="' + segmentationId + '" style="float:right; "><span  class="' + segmentationId +'" style="background-color: lightblue;">' + obj.description + '</span></div><hr style="background-color: lightgrey;" class="segmentation2" speakerId="' + obj.description+ '" speakerTimestamp="' + obj.timestampSeconds + '">');
                        // check first if we have a speaker separation already...
                        //var sentenceList = $("#transcript > div[s=" +sentenceId + "]");
                        var sentenceList = $( "div[s=" +sentenceId + "]" );

			var sentence = $(sentenceList[0]);
			var sentencePrev = sentence.prev();
                        if (sentencePrev.hasClass(segmentationId)) {
                                //var previous = $(sentence).prev().prev();
                                //var previous = sentence.prev().prev();
				var previous = sentencePrev.prev();

				var previousContent = previous.html();
                                previous.html(previousContent + ' <span class="' + segmentationId + '" style="background-color:lightblue;"> ' + obj.description + '</span>');

                        } else {
                                newDelimiter.insertBefore(sentenceList);
				//newDelimiter.insertBefore("#transcript > div[s=" +sentenceId +"]");
                        }

}



 function sayHello(obj) {
                console.log("Say Hello!");
        }


 // setup the right document id to be able to load META data - using global variable!!!
 var myDocId = docid.split('.').slice(0, -1).join('.').split('_').slice(0, -1).join('_');
 console.log("Local doc id: " + myDocId);


var globalLastPosition = -1;

 function loadJSON(callback) {

    var xobj = new XMLHttpRequest();
        xobj.overrideMimeType("application/json");
    xobj.open('GET', myDocId + '.timeline.json', true); // Replace 'my_data' with the path to your file
    xobj.onreadystatechange = function () {
          if (xobj.readyState == 4 && xobj.status == "200") {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            callback(xobj.responseText);
            $(".segmentationButton").show();
          } else {
                console.log("There was a problem getting marker JSON data");
          }
    };
    xobj.send(null);
 }



 loadJSON(function(response) {
                // Parse JSON string into object
                //console.log(response)
		var markers_JSON = JSON.parse(response);

                console.log("");
                console.log("--- MARKERS ---");
                //console.log(markers_JSON);
		console.log("STARTING loadJSON");
		
                var lastPosition = -1;
		lastPosition = globalLastPosition;

                //markers_JSON.markers.forEach(function(response) { sayHello(response) } );

		//var markerId = "#markersList";
		//var markersList = $(markerId);
		//console.log("Markers object: " );
		//console.log(markersList);

                markers_JSON.markers.forEach(function(response, lastPosition, markersList) {  parseSpeakers(response, "markersList", "segmentation", lastPosition); } );

});







