//script for audio sync
var AudioSync = {};
var brTagFlag = false;		//if true dont combine readlist again
var defaultImg = 'default.png';
var imgArray=[];
var originalArr = [];				//images which is selected on left side bar
AudioSync.ackGroupArr =['Author','Illustrator','Writter']
Acknowledgement =
{
	'Author': 'xyz',
	'Writter':'abc'	,
	'Author1': 'xyz',
	'Writter1':'abc'	
}
$(document).ready(function()
{ 
	$('.loader').css('display', 'flex');
	AudioSync.is_edited = false;

	$('#storybox').bind('mouseup', function (e) {
		var selection;

		if (window.getSelection) {
			selection = window.getSelection();
		} else if (document.selection) {
			selection = document.selection.createRange();
		}
		if (selection != '')
			AudioSync.colorSentence(e);
		else{
			$('#iconDiv').hide();
		}
	});
	
});

window.onload = function(){

	AudioSync.pageCounter=0;
	AudioSync.playStoryFlag=false;
	AudioSync.stopHighlightFlag=false;
	$('[data-toggle="tooltip"]').tooltip({ trigger: "hover" });   
	$("#play").tooltip().attr('data-original-title', 'Play');
	AudioSync.createImgList();
	// $('.tickMark').removeClass('clickedImg');
	AudioSync.showTickMark();
	if (storyImages.length == 0)
    {
        $(".imageBar,.imgDiv").hide();
        $(".txtDiv").prop('class','noPadding col-12 txtDiv')
    }
    else
		$(".txtDiv").prop('class','noPadding col-8 txtDiv')
		
	if(storyJson[AudioSync.pageCounter].pageImage=='')
		$('#pageImg').prop('src',static_imgurl+ defaultImg);
	
	var arr = JSON.stringify(storyJson);
	originalArr = JSON.parse(arr);

	AudioSync.initialisePage();
}

function loadedeverything(){
	$('.loader').hide();	
}

AudioSync.createImgList = function ()			//create left side image div's
{
	var imgDiv, img, iTag;
	for (var i = 0; i < storyImages.length; i++)
	{
		imgDiv = document.createElement('div');
		imgDiv.setAttribute('class', 'leftImgDiv roundedCorn');
		imageList.appendChild(imgDiv);
		
		img = document.createElement('img');
		img.setAttribute('class', 'col-12');
		img.setAttribute('src', media_path + storyImages[i]);
		img.setAttribute('title',storyImages[i]);
		img.setAttribute('onclick', 'AudioSync.selectImg(this);');
		imgDiv.appendChild(img);

		iTag = document.createElement('i');
		iTag.setAttribute('class', 'fa fa-check-circle-o m-1 tickMark');
		$(iTag).css('position', 'absolute');
		imgDiv.appendChild(iTag);
	}
}

AudioSync.initialisePage=function(){
	
	$('#actionwidgets').css({ 'pointer-events': 'none' });
	$('#addPage,#deletePage').css({'pointer-events':'auto'});
	$('#play').children('i').removeClass().addClass('fa fa-play');//text('play_arrow');
	$('#iconDiv').hide();
	document.getElementById('playSound').load();
	AudioSync.showPageText();
};

//show text on page 
AudioSync.showPageText=function()
{
	$('#pageText').empty();
	//AudioSync.pagesArr=storyJson.slice();
	var counter = 0;
	AudioSync.pageDuration = 0, AudioSync.wordCounter = 0, AudioSync.pageStartTime = 0;
	AudioSync.readNode = storyJson[AudioSync.pageCounter]['pagedata'][0]['readList'];	//get combined readlist
	AudioSync.noOfWords = AudioSync.readNode.length;
 
	for (var j = 0; j < storyJson[AudioSync.pageCounter]['pagedata'][0].readList.length; j++) {
		if (storyJson[AudioSync.pageCounter]['pagedata'][0]['readList'][counter].word != '<br>') {
			var span = document.createElement('span');
			span.setAttribute('id', 'span' + counter);
			span.style = "margin-left:1vw;font-size:2vw;color:#887878;";
			$(span).text(storyJson[AudioSync.pageCounter]['pagedata'][0]['readList'][counter].word + " ");
			span.setAttribute('class', 'pageWords');
		}
		else {
			var span = document.createElement('br');
			span.setAttribute('id', 'span' + counter);
		}
		$('#pageText').append(span);
		counter++;
	}
	
	$('#actionwidgets').css({ 'pointer-events': 'auto' });
	if (AudioSync.readNode.length != 0)
		AudioSync.pageStartTime = parseFloat(AudioSync.readNode[AudioSync.wordCounter]['wordFrom']);
	var pageNo = (AudioSync.pageCounter + 1) + '/' + storyJson.length;

	$('#pageNo').text(pageNo);

	if (storyJson[AudioSync.pageCounter].pageImage != '') {
		imgArray[AudioSync.pageCounter] = storyJson[AudioSync.pageCounter].pageImage;
		$('#pageImg').prop('src', media_path + storyJson[AudioSync.pageCounter].pageImage);
		$('#pageImg').prop('title', storyJson[AudioSync.pageCounter].pageImage);
		// AudioSync.selectImg();
	}
	
}

//color the sentence and show next previous icon
AudioSync.colorSentence=function(event)
{
	var x = 0, y = 0;
	x = event.clientX;
	y = event.clientY;
	$('#iconDiv').css({ top: y - 50, left: x }).show();
	$('#newline').show();
};


//add new line to the page
AudioSync.addNewLine=function()
{
	AudioSync.stopPlayBack();
	brTagFlag = true;
	var sel = window.getSelection();
	var selectedSentence = sel.toString().split(' ');
	if (selectedSentence[selectedSentence.length - 1] == "")
		selectedSentence.splice(selectedSentence.length - 1, 1);
	for (var i = 0; i < sel.rangeCount; i++)
		startingIndex = Number((sel.getRangeAt(i).startContainer.parentNode.id.match(/\d+/g).map(Number)).toString());

	var wordobj = {};
	wordobj['wordId'] = 0;
	wordobj['word'] = '<br>';
	wordobj['wordFrom'] = '0';
	wordobj['wordTo'] = '0';
	wordobj['wordDuration'] = '0'

	storyJson[AudioSync.pageCounter]['pagedata'][0]['readList'].splice(startingIndex + selectedSentence.length, 0, wordobj);

	$('#iconDiv').hide();
	AudioSync.is_edited = true;
	AudioSync.initialisePage();
}

//onclick of next previous icon which is displayed on a sentence
AudioSync.shiftSentence=function(ele)
{
	AudioSync.stopPlayBack();
	$('#iconDiv').hide();
	AudioSync.is_edited = true;

	var sel = ''; var startingIndex = 0;
	sel = window.getSelection();
	selectedSentence = sel.toString().split(' ');
	for (var i = 0; i < sel.rangeCount; i++) {
		startingIndex = Number((sel.getRangeAt(i).startContainer.parentNode.id.match(/\d+/g).map(Number)).toString());
	}

	if (selectedSentence[selectedSentence.length - 1] == "")
		selectedSentence.splice(selectedSentence.length - 1, 1);

	if (ele == 'nextIcon')
		AudioSync.moveToNextPage(startingIndex);
	else
		AudioSync.moveToPrevPage(startingIndex);
	AudioSync.showPageText();
};

AudioSync.moveToNextPage=function(startingIndex)		//move sentence to the next page
{
	var pageWordLength = $('#pageText').children().length;
	var splicedArr = storyJson[AudioSync.pageCounter]['pagedata'][0].readList.splice(startingIndex, pageWordLength);

	if (AudioSync.pageCounter < storyJson.length - 1) {
		splicedArr.reverse();
		for (var i = 0; i < splicedArr.length; i++)
			storyJson[AudioSync.pageCounter + 1]['pagedata'][0].readList.unshift(splicedArr[i]);
	}
	else {									//if last page create new node
		var pagesObj = {};
		var pages=[];
		var page={};
		pagesObj['pageImage'] = '';
		page["readList"] = splicedArr;
		pages.push(page);
		pagesObj['pagedata']=pages;
		storyJson.push(pagesObj);
		AudioSync.pageCounter++;
		$('#pageImg').prop('src', static_imgurl + defaultImg);
	}

	if (storyJson[AudioSync.pageCounter]['pagedata'][0].readList.length == 0)
		AudioSync.deleteCurrentPage();
	console.log(storyJson);
}
	
AudioSync.moveToPrevPage=function(startingIndex)			//move sentence to the prev page
{
	brTagFlag = false;
	var pageWordLength = $('#pageText').children().length;
	var splicedArr = storyJson[AudioSync.pageCounter]['pagedata'][0].readList.splice(0, Number(selectedSentence.length + startingIndex));

	if (pageWordLength == 0)
		AudioSync.deleteCurrentPage();

	if (AudioSync.pageCounter != 0) {
		for (var i = 0; i < splicedArr.length; i++)
			storyJson[AudioSync.pageCounter - 1]['pagedata'][0].readList.push(splicedArr[i]);	
	}
	else {									//if first page create new node
		var pagesObj = {};
		var pages=[];
		var page={};
		if (storyJson[AudioSync.pageCounter].pageImage != '')
			pagesObj['pageImage'] = imgArray[AudioSync.pageCounter];
		else
			pagesObj['pageImage'] = '';
		page["readList"] = splicedArr;
		pages.push(page);
		pagesObj['pagedata']=pages;
		storyJson.unshift(pagesObj);
		AudioSync.pageCounter++;
		storyJson[AudioSync.pageCounter].pageImage = '';
		$('#pageImg').prop('src', static_imgurl + defaultImg);
	}
}

//add page on click of addpage button
AudioSync.addNewPage=function()
{
	var pagesObj={};
	var pages={};
	var pagedata=[];
	pages['pageImage']='';
	pagesObj['sentence'] = '';
	pagesObj['readList']=[];
	pages['pagedata'] = pagedata;

	$('#iconDiv').hide();
	AudioSync.pageCounter++;
	$('#pageText').empty();
	$('#pageImg').prop('src',static_imgurl+ defaultImg);
	var pageNo=(AudioSync.pageCounter+1)+'/'+storyJson.length;
	$('#pageNo').text(pageNo);
	storyJson.splice(AudioSync.pageCounter, 0, pages);
	imgArray.splice(AudioSync.pageCounter, 0, static_imgurl+defaultImg);
	AudioSync.readNode=storyJson[AudioSync.pageCounter]['pagedata'][0]['readList'];
	AudioSync.noOfWords=AudioSync.readNode.length;
}

//delete page on click of delete page button
AudioSync.deleteCurrentPage=function()
{
	$('#iconDiv').hide();
	AudioSync.is_edited = true;
	storyJson.splice(AudioSync.pageCounter,1);
	if(AudioSync.pageCounter>0)
		AudioSync.pageCounter--;
	$('#pageText').empty();
	
	if (imgArray.includes($('#pageImg').prop('title')))		//image is used or not 
	{
		var count=0
		for(var i = 0; i < imgArray.length; i++){
			if(imgArray[i] == $('#pageImg').prop('title'))
				count++;
		}
		imgArray.splice(imgArray.indexOf($('#pageImg').prop('title')), 1);
		if (count == 1)
			AudioSync.selectImg()
	}
	$('#pageImg').prop('src', static_imgurl+defaultImg);
	if(storyJson.length!=0)
		AudioSync.showPageText();
	else
	{
		$('#addPage').css({'pointer-events':'none'});
		alert('Story has no pages');
	}
};
AudioSync.showTickMark= function ()
{
	for(var i=0;i<storyJson.length;i++)
		imgArray[i]=storyJson[i].pageImage;
	for(var k=0;k<imgArray.length;k++)
	{
		for(var j=0;j<$("#imageList").children().length;j++)		//mark image if it is used
		{
			if(imgArray[k]==$($($("#imageList").children()[j]).children()[0]).prop('title'))
				$($($("#imageList").children()[j]).children()[1]).css('visibility','visible')
		} 
	}
}
AudioSync.selectImg=function(img)		//images which is selected on left side bar
{
	AudioSync.is_edited=true;
	$('.tickMark').css('visibility', 'hidden');
	if (img != undefined)
	{
		$('#pageImg').prop('src',media_path+img.title);
		$('#pageImg').prop('title',img.title);
		storyJson[AudioSync.pageCounter]['pageImage'] = img.title;
	}
	AudioSync.showTickMark();

	/* AudioSync.is_edited=true;
	$('.tickMark').css('visibility', 'hidden');
	if (img != undefined)
	{
		if (!$($(img).parent().children()[1]).hasClass('clickedImg'))
			$($(img).parent().children()[1]).addClass('clickedImg');

		$('#pageImg').prop('src',media_path+img.title);
		$('#pageImg').prop('title',img.title);
		storyJson[AudioSync.pageCounter]['pageImage'] = img.title;
	}
		
	for(var i=0;i<storyJson.length;i++)
		imgArray[i]=storyJson[i].pageImage;
	for(var k=0;k<imgArray.length;k++)
	{
		for(var j=0;j<$("#imageList").children().length;j++)		//mark image if it is used
		{
			if($($($("#imageList").children()[j]).children()[1]).hasClass('clickedImg') && (imgArray[k]==$($($("#imageList").children()[j]).children()[0]).prop('title')))
				$($($("#imageList").children()[j]).children()[1]).css('visibility','visible')
		} 
	} */
};

AudioSync.playStory=function()
{
	$('#iconDiv').hide();
	$('#pageText').children().children().css({'background-color':'transparent'});
	if(AudioSync.playStoryFlag)
		AudioSync.pausePage();
	else if(!AudioSync.playStoryFlag && AudioSync.readNode.length!=0)
	{
		$("#play").attr('data-original-title', 'Pause').tooltip('show');
		$("#play").tooltip('show');
		AudioSync.playStoryFlag=true;
		AudioSync.stopHighlightFlag=false;
		$('#addPage,#deletePage,.clickableSpans').css({'pointer-events':'none'});
		$('#addPage,#deletePage').css('opacity','0.5');
		$('#play').children('i').removeClass().addClass('fa fa-pause');
		document.getElementById('playSound').load();
		document.getElementById('playSound').currentTime=AudioSync.pageStartTime;
		var i=1;
		while(AudioSync.readNode[AudioSync.noOfWords-i].word.trim() == '<br>')
			i++;
		AudioSync.pageDuration=(parseFloat(AudioSync.readNode[AudioSync.noOfWords-i]['wordTo'])-AudioSync.pageStartTime)*1000;
		AudioSync.playThisPage();
	}
};

AudioSync.playThisPage=function(){
	$('#playSound').trigger('play');
	if(AudioSync.pageTimer){
		clearTimeout(AudioSync.pageTimer);
		AudioSync.pageTimer=null;
	}
	AudioSync.pageTimer=setTimeout(function()
	{
		AudioSync.stopPlayBack();
	},AudioSync.pageDuration);
	console.log('Audio Played at '+AudioSync.pageStartTime+' ,'+AudioSync.wordCounter+' '+AudioSync.pageDuration);
	if(AudioSync.readNode.length!=0)
		AudioSync.highlight();
};

AudioSync.pausePage=function()
{
	$("#play").attr('data-original-title', 'Play').tooltip('show');
	$("#play").tooltip('show');
	AudioSync.playStoryFlag=false;
	$('#playSound').trigger('pause');
	clearTimeout(AudioSync.pageTimer,AudioSync.timer);
	$('#play').children('i').removeClass().addClass('fa fa-play');
	AudioSync.pageStartTime=document.getElementById('playSound').currentTime;
	AudioSync.pageDuration=(parseFloat(AudioSync.readNode[AudioSync.noOfWords-1]['wordTo'])-AudioSync.pageStartTime)*1000;
	console.log('Audio Paused at '+AudioSync.pageStartTime+' ,'+AudioSync.wordCounter+' '+AudioSync.pageDuration);
};

AudioSync.stopPlayBack=function()
{
	$('#playSound').trigger('pause');
	clearTimeout(AudioSync.pageTimer, AudioSync.timer);
	$("#play").attr('data-original-title', 'Play').tooltip('show');
	$("#play").tooltip('hide');
	$('#play').children('i').removeClass().addClass('fa fa-play');
	AudioSync.playStoryFlag=false;
	AudioSync.stopHighlightFlag=true;
	$('.pageWords').css({'color':'#887878'});
	AudioSync.wordCounter=0;
	console.log('Audio Stopped at '+AudioSync.wordCounter+' '+AudioSync.pageDuration);
	if(AudioSync.readNode.length!=0)
		AudioSync.pageStartTime=parseFloat(AudioSync.readNode[AudioSync.wordCounter]['wordFrom']);
};

AudioSync.showNext=function(ele)	//show next story page
{
	$('#actionwidgets').css({'pointer-events':'none'});
	if(ele=="prev"){
		if(AudioSync.pageCounter!=0)
			AudioSync.pageCounter--;
	}
	else{
		if(AudioSync.pageCounter<storyJson.length-1)
			AudioSync.pageCounter++;
	}
	AudioSync.stopPlayBack();
	$('#pageImg').prop('src',static_imgurl+defaultImg);
	AudioSync.initialisePage();
	document.getElementById('playSound').load();
};

AudioSync.highlight=function()
{
	if(AudioSync.playStoryFlag)
	{
		$('#span'+AudioSync.wordCounter).css({'color':'black'});
		document.getElementById('span'+AudioSync.wordCounter).scrollIntoView({behavior:"smooth"});
		if(AudioSync.wordCounter<AudioSync.noOfWords-1)
			duration=(AudioSync.readNode[AudioSync.wordCounter]['wordTo']-AudioSync.readNode[AudioSync.wordCounter]['wordFrom'])*1000;
		if(AudioSync.timer)
		{
			clearTimeout(AudioSync.timer);
			AudioSync.timer=null;
		}
		AudioSync.timer=setTimeout(function()
		{
			clearTimeout(AudioSync.timer);
			if(AudioSync.wordCounter<AudioSync.noOfWords-1 && AudioSync.stopHighlightFlag==false)
			{
				AudioSync.wordCounter++;
				AudioSync.highlight(AudioSync.wordCounter);
				return 0;
			}
			else{
				AudioSync.wordCounter=0;
			}
		},duration);
	}
};

AudioSync.checkBlankText=function()
{
	var flag=false;
    for(var i=storyJson.length-1;i>=0;i--)
    {
        if (storyJson[i].pagedata[0].readList.length==0){			
			storyJson.splice(i,1);
			flag=true;
		}
           
	}
	if(flag){
		AudioSync.pageCounter = 0;
    	AudioSync.showPageText();
	}
};

AudioSync.saveStory=function(){
	console.log(storyJson);
	AudioSync.stopPlayBack();
	AudioSync.checkBlankText();
	if(AudioSync.is_edited){
        $.ajax({
            type:'POST',
            url:'/savestorypages/'+$('#storyid').val()+'/',
            data:{
                storypages:JSON.stringify(storyJson),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(response){
				console.log(response);
				if(response=='404'){
					$('#deleteErrorModal').modal({
						backdrop:'static'
					});	
					$('#deleteErrorModal').modal('show');	
				}
				else{
					showSnackBar(response);
					AudioSync.is_edited=false;
					if(AudioSync.requestDownloadFlag)
						AudioSync.downloadStory()
				}   
            },
            error:function(){
                console.log('Error');               
			}
        });
    }
    
};

AudioSync.downloadStory=function(){

	AudioSync.requestDownloadFlag=false;
	if(AudioSync.is_edited){
		AudioSync.requestDownloadFlag=true;
		AudioSync.saveStory();
	}		
	else
	{
		AudioSync.stopPlayBack();
		AudioSync.sendRequestToDownload();
	}	
}

AudioSync.sendRequestToDownload=function(){
	$('.loader').css('display', 'flex');
	$.ajax({
		type:'POST',
		url:'/downloadstory/'+$('#storyid').val()+'/',
		data:{
			csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
		},
		success:function(response){
			console.log(response);
			if(response=='404'){
				$('#deleteErrorModal').modal({
					backdrop:'static'
				});	
				$('.loader').hide();
				$('#deleteErrorModal').modal('show');
			}
			else{
				window.open(response, '_blank');
				$('.loader').hide();
			}			 
		},
		error:function(){
			console.log('Error');               
		}
	});
}

AudioSync.cancelStep = function (element)
{
	AudioSync.stopPlayBack();
	$("#play").tooltip('hide');
	confirmModalFun(element);
}

AudioSync.reset = function () {
	if (AudioSync.is_edited) {
		AudioSync.stopPlayBack();
		imgArray = [];
		$('.tickMark').css('visibility', 'hidden');
		// $('#pageImg').prop('src',static_imgurl+defaultImg);
		var arr = JSON.stringify(originalArr);
		storyJson = JSON.parse(arr);
		AudioSync.pageCounter = 0;
		AudioSync.showPageText();
	}
}
/* ------------------------------------------------------------- */

AudioSync.editAck = function (element) {
	$(".ackRows,.previousAck,#ackGroup").empty();
	AudioSync.stopPlayBack();
	$("#play").tooltip('hide');
	AudioSync.showPrevAckRows();		
	AudioSync.createAckGroup();
	confirmModalFun(element);
}
AudioSync.showPrevAckRows = function (element) {
	
	for (let i = 0; i < Object.keys(Acknowledgement).length; i++) {
		var div,label, input1,input2 ,dltIcon;
		div = document.createElement('div')
		$(div).prop('class', 'col-10 offset-1 d-flex justify-content-around align-items-center my-1');
		
		input1 = document.createElement('input');
		$(input1).prop('type', 'text');
		$(input1).prop('class', 'modalAck text-center');
		$(input1).val(Object.keys(Acknowledgement)[i]);
		
		$(input1).css({ 'width': '20%'});
		$(div).append(input1);
		$(div).append('<span>:</span>');

		input2 = document.createElement('input');
		$(input2).prop('type', 'text');
		$(input2).prop('class', 'modalAck text-center');
		$(input2).val(Object.values(Acknowledgement)[i]);
		$(input2).css('width', '60%');
		$(div).append(input2);

		dltIcon = document.createElement('i');
		$(dltIcon).prop('class', 'fa fa-trash');
		$(dltIcon).data('value', 'prev');
		$(dltIcon).css('font-size', '1.7vw');
		$(dltIcon).click(function () {
			AudioSync.deleteAck(this);
		})
		$(div).append(dltIcon);
		$(".previousAck").append(div);
	}
}
AudioSync.createAckGroup = function ()		//select dropdown
{
    var option;
    for (var i = 0; i < AudioSync.ackGroupArr.length; i++)
    {
        option = document.createElement('option');
        if (i == 0)
            $(option).prop('selected', true);
        $(option).prop('value', AudioSync.ackGroupArr[i]);
        $(option).text(AudioSync.ackGroupArr[i]);
        $('#ackGroup').append(option);
    }
}
AudioSync.resetAcknowledgment = function ()		//reset to original
{
	$('.ackRows,.previousAck').empty();
	AudioSync.showPrevAckRows();
	tempAcknowledgement = JSON.parse(JSON.stringify(Acknowledgement));
}
AudioSync.saveAcknowledgment = function ()
{
	tempAcknowledgement = {};
	for (let i = 0; i < $('.previousAck').children().length; i++) {
		tempAcknowledgement[$($($('.previousAck').children()[i]).children()[0]).val()]=$($($('.previousAck').children()[i]).children()[2]).val();
	}
    for (var i = 0; i < $('.ackRows').children().length; i++)
    {
        if ($($($('.ackRows').children()[i]).children()[0]).val() != '' && $($($('.ackRows').children()[i]).children()[2]).val() != '') //check if left & right side values are not empty
        {
			tempAcknowledgement[$($($('.ackRows').children()[i]).children()[0]).val()]=$($($('.ackRows').children()[i]).children()[2]).val();
        }
	}
	console.log( _.isEqual(tempAcknowledgement, Acknowledgement) );
	/* $.ajax({
        type:'POST',
        url:'/updateAcknowledgement/',
        data:{
            updatedAck:JSON.stringify(tempAcknowledgement),
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success:function(response){
            showSnackBar('Acknowledgement Updated');
       },
        error:function(){
            console.log('Error');
        }
	});
	console.log(tempAcknowledgement) */
}
AudioSync.addAckRows = function (element)			//add new acknowledgement
{
	
    var div,label, input, dltIcon;
    div = document.createElement('div')
    $(div).prop('class', 'col-11 offset-1 d-flex justify-content-around align-items-center my-1');
    
    label = document.createElement('input');
    $(label).prop('type', 'text');
    $(label).prop('class', 'labelTxt chkInput modalAck');
    
    if (element.id == 'selectedAck') {
        $(label).val($("#ackGroup").val());
        $(label).prop('disabled', true);
        $(label).css({ 'background': 'transparent'})
    }
    $(label).css({ 'width': '20%', 'text-align': 'center' });
    $(div).append(label);
    $(div).append('<span>:</span>');

    input = document.createElement('input');
    $(input).prop('type', 'text');
    $(input).prop('class', 'chkInput modalAck');
    $(input).css('width', '60%');
    $(div).append(input);

    dltIcon = document.createElement('i');
    $(dltIcon).prop('class', 'fa fa-trash');
	$(dltIcon).data('value', 'new');
	$(dltIcon).css('font-size', '1.7vw');
    $(dltIcon).click(function () {
        AudioSync.deleteAck(this);
    })
    $(div).append(dltIcon);
    $(".ackRows").append(div);
   /*  $('.chkInput').bind('keyup blur', function() {      // only alphabets
        $(this).val(function(i, val) {
            return val.replace(/[^a-z\s]/gi,''); 
        });
    }); */
    $(".ackRows").animate({ scrollTop: $(".ackRows")[0].scrollHeight}, 10);
}
AudioSync.deleteAck = function (element)
{
	var key = $($(element).parent()).children()[0].value;
	delete tempAcknowledgement[key];
	$($(element).parent()[0]).remove();
}
	
/* ------------------------------------------------------------- */

/* 
AudioSync.reset = function () {
	AudioSync.stopPlayBack();
	imgArray = [];
	$('.tickMark').css('visibility', 'hidden');
	$('#pageImg').prop('src',static_imgurl+defaultImg);
	if (!(storySavedFlag)) {
		storySavedFlag = true;
		var arr = JSON.stringify(AudioSync.originalArr);
		AudioSync.pagesArr = JSON.parse(arr);
		storyJson = JSON.parse(arr);
		AudioSync.pageCounter = 0;
		AudioSync.showPageText();
	}
} */