var checkedValues = '';

$(document).ready(function () {
    /***scroll to top */
    $(window).scroll(function () {
        if ($(this).scrollTop() > 50) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });
    
    $('#imgPreview').prop('src',static_link+'preview.png');
    // scroll body to 0px on click
    $('#back-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 400);
        return false;
    });
    
    $("#myModal").modal({backdrop: "static"});
    $("#myModal").modal('show');
    getCategory();
});

function show_uploading_form(){
    $("#myModal").modal('hide');
}

function close_page(){
    window.close();
}

function browseImage(ele){
    const file = ele.files[0];
    if (file && file.size< 10485760) {
        let reader = new FileReader();
        reader.onload = function (event) {
            $("#imgPreview")
            .attr("src", event.target.result);
            $('.custom-file-label').text(file.name)
            //console.log(file.size);
        };
        reader.readAsDataURL(file);
    }
    else{
        alert('image size should be less than 10mb')
    }
};

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 () {
//             $('#dropdownBtn').text(this.text);
//             $('#categoryName').val(this.text);
//             $('#categoryName').text(this.text);
//         })
//     }
// }

function createCategory(categoryArr) {
    for (var i = 0; i < categoryArr.length; i++) {
        // var ele = document.createElement('span');
        // $(ele).prop('class','input-group-text');
        // $(ele).text(categoryArr[i]);
        $('.dropdown-menu').append('<span class="input-group-text"><input type="checkbox" style="font-size: 17px;margin-right:6px;" class="checkboxes" onclick="getValues(this);" value="'+categoryArr[i]+'"></br><label style="margin-bottom:0px;">'+categoryArr[i]+'</label></span>');
    }
    $('.dropdown-menu').append('<div style="background-color:#e9ecef;position: sticky;bottom: 0;text-align:center;"><button type="button" class="btn btn-primary">Okay</button></div>');
}

function getValues(ele)
{
    checkedValues = $('.checkboxes:checked').map((i, ele) => ele.value).get();
    console.log(checkedValues);
    if(checkedValues.length==0){
        $('#dropdownBtn').text('Select category');
    }
    else if(checkedValues.length>=7){
        $('#dropdownBtn').text(checkedValues.length+' categories');
    }
    else
        $('#dropdownBtn').text(checkedValues.join(',')); 

    $('#categoryName').text(checkedValues.join(','));
    $('#categoryName').val(checkedValues.join(','));
    
}

// function close_category_dropdown(){
//     $().hide();
// }


function toggleCategory(){
    if($('#newCategory').val()=='')
        $('#dropdownBtn').prop( "disabled", false );
    else
        $('#dropdownBtn').prop( "disabled", true );
}

function validateForm(){
    if(($('#customFile').val() !='') && ($('#categoryName').val() != '' ) && ($('#tag').val() !='') && ($('#credit').val() != '') && ($('#consent').is(':checked')) && ($('input[name=creator_type]').is(':checked'))){
        return true;
    }
    else
        return false;
}

function submitForm(){
    if(validateForm())
    {
        $('#formValidation').text('');
        var data = new FormData($('#imageForm').get(0));
        $("#loader").show();
        $.ajax({
            url:'',
            type:'POST',
            data: data,
            cache: false,
            processData: false,
            contentType: false,
            success:function(response){
                if(response=='Error'){
                    //console.log('Error');
                }
                else{
                    //console.log(response);
                    resetForm();
                    $("#loader").hide();
                    showSuccessToast();                    
                }
                
            },
            complete:function(){
            },
            error:function (){
            }
        });
    }
    else
        $('#formValidation').text('Please fill all * fields');
}


function resetForm(){
    var form= document.getElementById('imageForm');
    $('.custom-file-label').text('');
    $('#dropdownBtn').text('Select category');
    $('#categoryName').val('');
    $('#imgPreview').prop('src',static_link+'preview.png');
    $('#dropdownBtn').prop( "disabled", false );
    $('#newCategory').prop( "disabled", false );
    form.reset();
}

function showSuccessToast() {
    var ele = document.getElementById("toast");
    $(ele).text("Image added successfully");
    ele.className = "show";
    setTimeout(function(){ 
        ele.className = ele.className.replace("show", ""); 
        location.reload(true);
    }, 3000);
}