var AudioSync = {};
AudioSync.storyList = [];
var nextCnt = 1, pageCnt, endIndex = 10, startIndex = 10,storyOrder = dateOrder=true;           //flag for asc desc order;;
$(document).ready(function () {
    //document.getElementById('langGroup').selectedIndex = "0";
    AudioSync.selectLang()
    $(window).scrollTop(0);
});
$(window).scroll(function () {
    if ($(window).scrollTop() > 0)
        $(".homeMenu").css({ "background": "linear-gradient(to right, #480048, #C04848", "transition": "all 0.3s ease-in-out"});
    else
        $(".homeMenu").css({ "background": "", "transition": "none", "padding": "2px 8px" })
});
AudioSync.selectLang = function () {
    $('.storyMenu,.sortCls').css('visibility', 'visible');
    $('.loader').css('display', 'flex');
    $('.mainDiv').empty();
    $("#searchstory").val('');
    /*   $.ajax({
          type:'POST',
          url:'/getstories/',
          data:{
              language:$('#langGroup option:selected').val(),
              csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
          },
          success:function(response){
              AudioSync.storyList=JSON.parse(response);
              console.log(); */
    if (AudioSync.storyList.length != 0) {
        AudioSync.createMenuDivs();
        $('.serachBox').css('visibility', 'visible');
        $('.loader').hide();
    }
    else {
        $('.loader').hide();
        $('.serachBox').css('visibility', 'hidden');
        showSnackBar('No Stories Found!');
    }
    /*  },
     error:function(){
         console.log('Error');
     }
 }); */
}
AudioSync.createPageNum = function () {                              //create page numbers
    var li, a;
    $('.pagination').empty();
    li = document.createElement('li');
    $(li).prop("class", "page-item prev");
    $(li).click(function () { AudioSync.pageAction(this); });
    a = document.createElement('a');
    $(a).prop("href", "#");
    $(a).prop("class", "page-link");
    $(a).text("Prevoius");
    $(li).append(a);
    $(".pageList").append(li);

    for (var i = 1; i <= pageCnt; i++) {
        var li = document.createElement('li');
        $(li).prop("class", "page-item number");
        $(li).data("value", i);
        $(li).click(function () { AudioSync.pageAction(this); });
        var a = document.createElement('a');
        $(a).prop("href", "#");
        $(a).prop("class", "page-link");
        $(a).text(i);
        $(li).append(a);
        if (i == 1) {
            $(li).addClass('active numCls');
            $(li).children().css("color", "white");
            $('.prev').css({ "pointer-events": "none" });
            $('.prev').children().css({ "color": "gray" });
        }
        $(".pageList").append(li);
    }
    li = document.createElement('li');
    $(li).prop("class", "page-item next");
    $(li).click(function () { AudioSync.pageAction(this); });
    a = document.createElement('a');
    $(a).prop("href", "#");
    $(a).prop("class", "page-link");
    $(a).text("Next");
    $(li).append(a);
    $(".pageList").append(li);
    if (AudioSync.storyList.length < 5) {
        $('.next,.prev').css({ "pointer-events": "none" });
        $('.next,.prev').children().css({ "color": "gray" });
    }
}
AudioSync.tableRows = function (rowCnt) {                               //show page wise records
    endIndex = numToDivide, startIndex = numToDivide;
    // $(".dataTable,.showingResult").show();
    $(".mainDiv").children().hide();
    endIndex = (endIndex * rowCnt) - 1;
    startIndex = startIndex * (rowCnt - 1);
    for (var i = startIndex; i <= endIndex; i++) {
        if (AudioSync.storyList[i] !== undefined) {
            $($(".mainDiv").children()[i]).show();
        }
        else
            break;
    }
    endIndex = i;
    $(".showingResult").text("Showing " + (startIndex + 1) + " to " + endIndex + " of " + AudioSync.storyList.length + " entries");
}
AudioSync.pageAction = function (element) {                      //actoin performed onclick of page number
   /*  $("#lbl1").prop("checked", false);
    if (AudioSync.checkedAllFlag == true)
        $(".checkBox").prop("checked", false); */
    $(".page-item").removeClass("active numCls");
    $('.prev,.next').css({ "pointer-events": "auto" });
    $('.page-item').children().css("color", "#007bff");
    if (element.className.includes("number"))
        nextCnt = $(element).data("value");
    else if (element.className.includes("prev"))
        nextCnt--;
    else if (element.className.includes("next") && nextCnt < pageCnt) {
        nextCnt++;
    }
    $($(".pageList").children()[nextCnt]).addClass("active numCls");
    $($($(".pageList").children()[nextCnt]).children()).css("color", "white");
    if (nextCnt == pageCnt) {
        $('.next').css({ "pointer-events": "none" });
        $('.next').children().css({ "color": "gray" });
    }
    if (nextCnt == 1) {
        $('.prev').css({ "pointer-events": "none" });
        $('.prev').children().css({ "color": "gray" });
    }
    AudioSync.tableRows(parseInt($(".numCls").text()));
}
AudioSync.onHoverOut = function ()
{
    $('.hoverClass').removeClass('addEffect');
    }
AudioSync.createMenuDivs = function () {
    var innerDiv, hoverDiv, whiteBtn, viewBtn,barIcon, dropDown,dropMenu, dropItem,storyName, writtenBy, illustratedBy, storyCover,updatedDate, imgCnt = 0;
    var dropItemArr = ['View Story', 'Edit Story', 'Delete Story'];
    var iconArr = ['book', 'pencil', 'trash'];
    $('.mainDiv').empty();
    for (var imgCnt = 0; imgCnt < AudioSync.storyList.length; imgCnt++) {
        innerDiv = document.createElement('div');
        $(".mainDiv").append(innerDiv);
        
        pageDiv = document.createElement('div');
        $(pageDiv).prop('id', imgCnt);
        $(pageDiv).prop('class', 'cardClass pb-3');
        $(pageDiv).prop('title', AudioSync.storyList[imgCnt].name);
        /* pageDiv.setAttribute('onmouseenter','AudioSync.onHover(this);')
        pageDiv.setAttribute('onmouseleave','AudioSync.onHoverOut();') */

        $(pageDiv).mouseover(function () {AudioSync.onHover(this); });
        $(pageDiv).mouseout(function () {
             //$('.hoverClass').removeClass('addEffect');
           // AudioSync.onHover(this)
        });
        $(pageDiv).data('pk', AudioSync.storyList[imgCnt]['id']);
        $(innerDiv).append(pageDiv);

        hoverDiv = document.createElement('div');
        $(hoverDiv).prop('class', 'hoverClass cardClass noPadding');
        $(innerDiv).append(hoverDiv);
        
        whiteBtn = document.createElement('div');
        $(whiteBtn).prop('class', 'whiteBtnCls');
        $(hoverDiv).append(whiteBtn);

        viewBtn = document.createElement('div');
        $(viewBtn).prop('class', 'viewCls');
        $(viewBtn).text('VIEW STORY');
        $(whiteBtn).append(viewBtn);

        dropDown = document.createElement('div');
        $(dropDown).prop('class', 'dropdown');
        $(whiteBtn).append(dropDown);

        barIcon = document.createElement('div');
        $(barIcon).prop('class', 'fa fa-ellipsis-v dropDownCls noPadding text-center dropdown-toggle');
        $(barIcon).attr('data-toggle', 'dropdown');
        $(dropDown).append(barIcon);

        dropMenu = document.createElement('div');
        $(dropMenu).prop('class', 'dropdown-menu dropdown-menu-right');
        $(dropDown).append(dropMenu);

        for (let index = 0; index < 3; index++) {
            dropItem = document.createElement('a');
            $(dropItem).prop('class', 'dropdown-item');
            if (index == 0)
            {
                $(dropItem).prop('href', '../viewstory/' + AudioSync.storyList[imgCnt]['id']);
                $(dropItem).prop('target', '_blank');
            }
            else if (index == 1)
            {
                // $(dropItem).attr('data-toggle','modal');
                // $(dropItem).attr('data-target','#editModal');  
                $(dropItem).data('pk',AudioSync.storyList[imgCnt]['id']);
                $(dropItem).click(function(){ AudioSync.editClicked(this); });
            }
            else
            {
                $(dropItem).addClass('deleteIcon');
                // $(dropItem).attr('data-toggle','modal');
                // $(dropItem).attr('data-target','#confirmModal');
                $(dropItem).click(function(){
                AudioSync.selectedStory=$($(this).parents()[4]).children()[0].id;
                AudioSync.storyId=$($($(this).parents()[4]).children()[0]).data('pk');
                AudioSync.dltModal(this);
            })
        }
        dropItem.innerHTML = '<i class="mr-3 fa fa-'+iconArr[index]+'" aria-hidden="true"></i><span>'+dropItemArr[index]+'</span>';
        $(dropMenu).append(dropItem);
    }
    storyCover = document.createElement('img');
    $(storyCover).prop('class', 'noPadding col-12 img-responsive');
    $(storyCover).css({ 'max-height': '60%', 'width': '100%' });
    if (AudioSync.storyList[imgCnt].icon == null)
        $(storyCover).prop('src', static_imgurl + 'story_ic.png');
    else
        $(storyCover).prop('src', AudioSync.storyList[imgCnt].icon);
    pageDiv.append(storyCover);

    storyName = document.createElement('div');
    $(storyName).prop('class', 'storyNames my-2 col-12');
    $(storyName).data('englishName', AudioSync.storyList[imgCnt].englishName);
    $(storyName).text(AudioSync.storyList[imgCnt].name);
    pageDiv.append(storyName);

    writtenBy = document.createElement('small');
    $(writtenBy).prop('class', 'my-2 col-12 d-block text-muted');
    $(writtenBy).text(AudioSync.storyList[imgCnt].writtenBy);
    pageDiv.append(writtenBy);

    illustratedBy = document.createElement('small');
    $(illustratedBy).prop('class', 'my-2 col-12 d-block text-muted');
    $(illustratedBy).text(AudioSync.storyList[imgCnt].illustratedBy);
    pageDiv.append(illustratedBy);
        
    updatedDate = document.createElement('small');
    $(updatedDate).prop('class', 'my-2 col-12 d-block text-muted');
    $(updatedDate).text(AudioSync.storyList[imgCnt].date);
    pageDiv.append(updatedDate);

    
    $("[data-tt=tooltip]").tooltip({ trigger: "hover" });
    }
    numToDivide = 15;    // 15 stories on one page
    if (AudioSync.storyList.length <= 25)                  // if less stories calculate page count
        pageCnt = Math.ceil(AudioSync.storyList.length / 15);  
    else                                              
        pageCnt = 5;    //if more stories then page count should be 5
    AudioSync.createPageNum();
    AudioSync.tableRows(parseInt($(".numCls").text()));
}
AudioSync.onHover = function (ele)
{
    if (AudioSync.onHover.caller.arguments[0].type == "mouseover")
    {
        AudioSync.globalEle = ele;
        $('.hoverClass').removeClass('addEffect');
        $(ele).siblings().addClass('addEffect');    
    }
    else
    {
         //$(AudioSync.globalEle).siblings().removeClass('addEffect');
        // $(ele).siblings().addClass('addEffect');    
        /* for (var i = 0; i < $('.mainDiv').children().length; i++)
        {
            if($($('.mainDiv').children()[i].children[1]).hasClass('addEffect'))
            $($('.mainDiv').children()[i].children[1]).removeClass('addEffect')
        } */
    }
    
}
AudioSync.editClicked = function (ele) {    //add into editclicked fun

	bootbox.dialog({
        title: 'Select the step',
        message: '<button class="my-2 bg-info mx-auto w-50 justify-content-center">Edit Highlighting</button><button class="bg-info mx-auto w-50 justify-content-center">Edit Story Pages</button>',
        backdrop:true,
    });

    /* var tempurl = $('#editspeechmarks').prop('href');
    tempurl = tempurl.split('editspeechmarks')[0];
    tempurl += 'editspeechmarks/' + $(ele).data('pk') + '/';
    console.log(tempurl);
    $('#editspeechmarks').prop('href', tempurl);

    tempurl = $('#editpages').prop('href');
    tempurl = tempurl.split('editstorypages')[0];
    tempurl += 'editstorypages/' + $(ele).data('pk') + '/';
    console.log(tempurl);
    $('#editpages').prop('href', tempurl); */
}
AudioSync.getDltTask = function (ele)            //get deleted items
{
    if ($(ele).prop('class').includes("dltUser"))               //onclick of delete icon
    {
        $(".checkBox,#chkAll").prop("checked", false);
        AudioSync.selectedRow = $(ele).parent().parent().data('rowData');    //get row number to delete the user
       var str= $($(ele).parent()).parent().children()[2].textContent.slice(0,20)
        AudioSync.dltModal(str+'...');
    }
    else  if ($(ele).prop('class').includes("deleteSelected"))       //onclick of delete selected button
    {
        AudioSync.selectedRow = null;
        var chkCnt = $("#dataTable").find('.checkBox').filter(':checked').length;  //get check count
        if (chkCnt == 0)
            showSnackBar("Please select the paragraph");
        else
            AudioSync.dltModal('the selected paragraph');
    }
}
AudioSync.dltModal = function ()
{
    bootbox.confirm({
        title: "Confirm deletion",
        message: "Are you sure you want to delete "+AudioSync.storyList[Number(AudioSync.selectedStory)].name+" ?",
        backdrop:true,
        buttons: {
            cancel: {
                label: '<i class="fa fa-times"></i> No'
            },
            confirm: {
                label: '<i class="fa fa-check"></i> Yse'
            }
        },
        callback: function (result) {
            if(result)
            AudioSync.deleteStory()
        }
    });
}
AudioSync.deleteStory = function () {
   /*  $.ajax({
        type: 'POST',
        url: '/deletestory/',
        data: {
            storyid: AudioSync.storyId,
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response) {
            console.log(response);
            $('.tooltip').remove(); */
            $('#' + AudioSync.selectedStory).parent().remove()
           /*  if (response == '404') {
                location.href = '../error/';
            }
            else
                showSnackBar(response);
        },
        error: function () {
            console.log('Error');
        }
    }); */
    console.log('hi');
}
AudioSync.searchStory = function()
{
    var input, filter, i, searchCnt = 0;
    $(".noRecord").hide();
    input = document.getElementById("searchstory");
    filter = input.value.toUpperCase();
    for (i = 0; i < $(".mainDiv").children().length; i++){
        storyname_lang = $($(".mainDiv").children()[i]).children().children()[1];
        storyname_english = $($($(".mainDiv").children()[i]).children().children()[1]).data('englishName');
        if (storyname_lang.innerHTML.toUpperCase().indexOf(filter) > -1 || storyname_english.toUpperCase().indexOf(filter) > -1)
            $($(".mainDiv").children()[i]).show();
        else {
            searchCnt++;
            $($(".mainDiv").children()[i]).hide();
        }
    }
    if (searchCnt == $(".mainDiv").children().length)
        $(".noRecord").show();
};
AudioSync.sort = function (order)
{
    var colorFlag = false;
    $('i').removeClass('asc desc');
    $($('#'+order.id).children()[0]).addClass('asc');
    $($('#' + order.id).children()[1]).addClass('desc');
    if (order.id == 'storyWise')
    {
        AudioSync.storyList = AudioSync.storyList.sort(GetSortOrder(order,storyOrder)); //Pass the attribute to be sorted on
        AudioSync.createMenuDivs();
        if (storyOrder) {
            colorFlag = true;
            storyOrder = false;
        }
        else
            storyOrder = true;
    }
            
    else
    {
        AudioSync.storyList = AudioSync.storyList.sort(GetSortOrder(order,dateOrder)); //Pass the attribute to be sorted on 
        AudioSync.createMenuDivs();
        if (dateOrder) {
            colorFlag = true;
            dateOrder = false;
        }
        else
            dateOrder = true;
    }
    if (colorFlag)
    {
        $('.desc').css('color', 'white');
        $('.asc').css('color', 'black');
    }
    else
    {
        $('.desc').css('color', 'black');
        $('.asc').css('color', 'white');
    }
}
//Comparer Function    
function GetSortOrder(order,flag) {    
    return function (a, b) {    
        var key1,key2
        if (order.id == 'storyWise') {
            key1 = a['englishName'];
            key2 = b['englishName'];
        }
        else
        {
            key1 = new Date(a['date']);
            key2 = new Date(b['date']);
        }
            if (flag==true && key1 >key2)
                return 1;        
            else if (flag==false &&  key1 <key2) 
                return 1;        
            else
                return -1;        
        } 
} 