var tableHeadings = ["Sr.No", "Images", "Acknowledgement", "Edit"];
var editFlag = false;
var initialiseDataTable = true;

$(document).ready(function () {
    /***scroll to top */
    $(window).scroll(function () {
        if ($(this).scrollTop() > 50) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });
    // scroll body to 0px on click
    $('#back-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 400);
        return false;
    });
    getCategory();
    
});

function getCategory() {
   
    $.ajax({
        type: 'GET',
        url: category_link,
        success: function (response) {
            console.log(response);
            var categoryArr = JSON.parse(response);
            createCategory(categoryArr);
        },
        error: function () {
            alert('Error');
        }
    });
}


function createCategory(categoryArr) {
    for (var i = 0; i < categoryArr.length; i++) {
        var a = document.createElement('a');
        $(a).prop('class', 'dropdown-item');
        $(a).text(categoryArr[i]);
        $('.dropdown-menu').append(a);
        $(a).on('click', function () {
            searchCategory(this)
        })
    }
}

function searchCategory(ele) {
    categoryName = $(ele).text();
    $("#loader").show();
    $('.dataTableDiv').hide();
    $('#dropdownBtn').text(categoryName);
    $('#categoryName').hide();
    $.ajax({
        type: 'GET',
        url: search_category_link,
        data: {
            keyword: categoryName,
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response) {
            $("#loader").hide();
            $('.dataTableDiv').show();
            var imageData = JSON.parse(response);
            console.log(imageData);
            $('#dataTable').empty();
            $('#categoryName').show();
            $('#categoryName').text('Showing ' + imageData.length + ' entries of ' + categoryName);
            createTable(imageData);
            showDataTable(); 
        },
        error: function () {
            alert('Error');
        }
    });

}

function createTable(imageData) {
    var thead, tr, th, tbody;
    thead = document.createElement('thead');                //thead
    tr = document.createElement('tr');
    for (var i = 0; i < tableHeadings.length; i++) {
        th = document.createElement('th');
        $(th).prop('id','tableHead'+(i+1));
        $(th).text(tableHeadings[i]);
        $(tr).append(th);
    }
    $(thead).append(tr);
    $("#dataTable").append(thead);

    tbody = document.createElement('tbody');
    $(tbody).prop('id', 'tableData');                    //tbody
    $("#dataTable").append(tbody);
    createTBody(imageData);
}

function showDataTable() {                              //show data table
    initialiseDataTable = false;         
    $('#dataTable').DataTable().destroy();
    $('#dataTable').removeAttr('width').DataTable({
        "autoWidth": false,
        "orderable": false,
        "columns": [
            { "width": "10%" },
            null,
            null,
            null
          ], 
        'columnDefs': [
        {
            orderable: false, 
            targets: [1,2,3] }
        ]
    });
    
    $('.dataTableDiv').show();
    
}

function createTBody(imageData)                     //tbody
{
    var idCnt;
    
    for (var i = 0; i < imageData.length; i++) {

        tr = document.createElement('tr');
        $(tr).data("rowData", i);
        $(tr).data("id", imageData[i]['id']);
        for (var k = 0; k < tableHeadings.length; k++) {
            td = document.createElement('td');
            $(tr).append(td);
        }
        $("tbody").append(tr);
        idCnt = 0;
        $($(tr).children()[idCnt]).html(i + 1); idCnt++;
        $($(tr).children()[idCnt]).html('<img data-toggle="modal" data-target="#myModal" data="'+imageData[i].url+'" onclick="showModal(this)" class="img-responsive imgThumbnail noPadding"  src=' + imageData[i].thumb_url + '>'); idCnt++;

        var input = document.createElement('input');
        $(input).prop('type', 'text');
        $(input).prop('class', ' my-1 ml-1 chip');
        /* $(input).prop('value', keywords[j]); */
        //$(input).text(keywords[j]);
        $(input).prop('disabled', true);
        $(input).val(imageData[i].credits);
        $(input).css({'width':'80%','height':'80px'});
        $($(tr).children()[idCnt]).append(input);

        var deleteIcon = document.createElement('i');
        $(deleteIcon).prop('class', 'icon deleteIcon fa fa-trash');
        $(deleteIcon).on('click', function () {
            delete_credits(this);
        })
        // $('.icon').css('visibility','hidden');
        $(deleteIcon).css('visibility','hidden');
        $($(tr).children()[idCnt]).append(deleteIcon);

        var span = document.createElement('span');
        $(span).css('display','none');
        $($(tr).children()[idCnt]).append(span);
        idCnt++;
        $($(tr).children()[idCnt]).html('<i class="fa fa-edit" onclick="edit_credits(this)"></i><i class="saveIcon fa fa-check" style="display:none;" onclick="save_credits(this)"></i>'); idCnt++;
    }
}

function edit_credits(ele) {
    editFlag = true;
   $(ele).css({'display':'none'});
   $(ele).next().css({'display':'block'});

    var eleData = $($(ele).parent()).parent().children()[2];

    var saveIconPath = $($(ele).parent()).siblings()[2]
    $($(eleData).find('.icon')).css('visibility','visible');
    
    $(eleData).find(".chip").prop('disabled', false);
    $(eleData).find(".chip").focus();
}


function save_credits(ele) {
   $(ele).css({'display':'none'});
   $(ele).prev().css({'display':'block'});


    var eleData = $($(ele).parent()).parent().children()[2];
    console.log(eleData);
    $($(eleData).find('.icon')).css('visibility', 'hidden');
    $(eleData).find(".chip").prop('disabled', true);
   
    
    var acknowledgement = $(eleData).find(".chip").val();
    $(eleData).find("span").text(acknowledgement);
    console.log(acknowledgement);

    url_link = credit_link + $(ele).parent().parent().data('id');
    
        $.ajax({
            type: 'POST',
            url: url_link,
            data: {
                credits: acknowledgement,
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (response) {
                console.log(response);
            },
            error: function () {
                alert('Error');
            }
        });
    
}

function showModal(ele) {
    var imageSrc = $(ele).attr('data');
    $('#modalImage').prop('src', imageSrc);
}

function delete_credits(ele){
    console.log($(ele));
    $($(ele).prev()).val(null);
}

