let imagesData= [];

function showfiltereddata(images)
{
    console.log('showing result');    
    $('#total_count').children('span').text(images.length);
    $('.imageGrid').empty();
    $('.imageGrid').css('display','flex');
    $('#total_count').show();
    createCols();
    var colNo=0;
    console.log(images.length);

    for (var i = 0; i < images.length; i++){
        createImgDivs(i, colNo,images);
        colNo++;
        if (colNo >= 5)
            colNo=0;      
    }
    if ($('.column').children().length == 0){
        $('.imageGrid').hide()
        $('.noRecord').show();
    }
}

function createCols()
{
    for (var i = 0; i < 5; i++) {
        var column
        column = document.createElement('div');
        $(column).prop('class', 'column col-2 noPadding');
        // $(column).prop('class', 'column noPadding');
        $(column).prop('id', 'column'+i);
        // $(column).prop('class', 'column');
        $('.imageGrid').append(column)
    }
}

function createImgDivs(cnt,colNo,imageData)
{
    var outerDiv, image;
    outerDiv = document.createElement('div');
    $(outerDiv).prop('class', 'outerDiv p-2 mb-3 rounded');
    // $(outerDiv).prop('class', 'outerDiv p-2 m-3 rounded');
    $(outerDiv).append('<i class="row fa fa-picture-o float-right" aria-hidden="true" style="font-size: x-large;"></i>');
    $('#column'+colNo).append(outerDiv)
    var anchor = document.createElement('a');
    anchor.href = search_link+imageData[cnt].id;
    anchor.target = "_blank";
    div = document.createElement('div');
    $(anchor).append(div);
    image = document.createElement('img');
    $(image).prop('src',imageData[cnt].thumb_url);
    // $(image).prop('class','img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12');
    $(image).prop('class','img-responsive');
    $(image).css('width','100%')
    $(div).append(image);
    $(outerDiv).append(anchor);
}

function searchImages_api(){
    imgName = $('input[name = search]').val();
    if(imgName!='')
    {
        //$('#validation,#main').hide();
        $('#main').hide();
        $('#searchImages').show();
        $.ajax({
            type:'GET',
            url:search_link,
            data:{
                keyword: imgName,
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(response){
                $('select').prop('disabled',false);
                console.log(response);
                imageData = JSON.parse(response);
                imagesData = imageData;
                showResult(imagesData);
            },
            error:function(){
                alert('Error');
            }
        });
    }
    else
    {
        $('.searchImg').focus();
        //$('#validation').show();
    }
}


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

function createSearchCategory(categoryArr){
    for(var i=0;i<categoryArr.length;i++){
        var option= document.createElement('option');
        $(option).text(categoryArr[i]);
        $(option).prop('value',categoryArr[i]);
        $('.category').append(option);
    }
    
}

function showFilteredCategory(ele){
    let selectedValue = $(ele).val();
    imagesData = imagesData.filter( (image) => {
        var splittedData = image.keyword.split(",");
        if(splittedData.includes(selectedValue))
            return image;
    })
    console.log(imagesData);
    showResult(imagesData);
}

function showBlackAndWhiteImages(ele){
    let selectedValue;
    images = []
    selectedValue = $(ele).val().toLowerCase();
    if(selectedValue!='colour' && selectedValue!='NA'){
        for(i =0;i<imagesData.length;i++){
            if(imagesData[i]['is_grey']==true)
                images.push(imagesData[i]);
        }
    }
    else{
        for(i =0;i<imagesData.length;i++){
            if(imagesData[i]['is_grey']==false)
                images.push(imagesData[i]);
        }
    }
    
    console.log(images);
    showfiltereddata(images);
}

function createTag(ele)
{
    var inputValue = $(ele).val().trim();
    if(inputValue.endsWith(',') && inputValue!=",")
    {
            arr = inputValue.split(",");
            if (arr[arr.length-2] != " "){
                var tag = document.createElement('div');
                $(tag).attr('data-placement',"top");
                $(tag).attr('class',"chip");

                keyword = document.createElement('div');
                $(keyword).text(arr[arr.length-2].trim());
                $(keyword).attr('title',arr[arr.length-2].trim());
                $(keyword).attr('class',"new_tags");
                $(keyword).css({'display':'inline-block'});

                $(tag).append(keyword);
                $(tag).append("<div class='closebtn' style='display:inline-block;' onclick='cancelDiv(this)'>&times</div>");
                $('#tags').append(tag);
                $(ele).val('');
            }
            
    }
}

function showKeywords()
{
    var anchor
    var savedTagsArr=$('.keywords').text().split(',');
    $('.keywords').text('');
    for (let i = 0; i <savedTagsArr.length; i++) {
        anchor=document.createElement('a');
        //   $(anchor).css({'background-color':'#c1d9ec','text-decoration':'none','cursor':'pointer'});
        $(anchor).prop('class','chip my-1 ml-1');
        // $(anchor).prop('class','mr-2 p-1 chip');
        // $(anchor).prop('target','_blank');
        // $(anchor).prop('href',"index.html");
        // $(anchor).click(function(){showResult(this)});
        $(anchor).text(savedTagsArr[i]);
        $('h5[name=current_keywords]').append(anchor);
    }
}

function edit_keywords()
{
    var tags_arr = [];
    $('#save_keywords').prop('style','display:inline-block;');
    $('#edit_keywords').prop('style','display:none;');

    $('h5[name=edit_current_keywords]').show();
    $('h5[name=current_keywords]').hide();
    $(".keywords > a").each(function(){
        if($(this).text()){
            tags_arr.push($(this).text());
        }
    });
    
    console.log(tags_arr);
    for (let i = 0; i <tags_arr.length; i++) 
    {
        anchor = document.createElement('input');
        //   $(anchor).css({'background-color':'#c1d9ec','text-decoration':'none','cursor':'pointer'});
        $(anchor).prop('class','chip my-1 ml-1 edited_keyword');
        $(anchor).prop('type','text');
        $(anchor).attr('value',tags_arr[i]);
        $(anchor).css({'border': 'none','width':'fit-content'});
        $(anchor).attr('size',$(anchor).val().length);
        // len = tags_arr[i].length;
        // if(len>5)
        //     $(anchor).prop('size',len-5);
        // else
        //     $(anchor).prop('size',len);
        // $(anchor).prop('class','mr-2 p-1 chip');
        // $(anchor).prop('target','_blank');
        // $(anchor).prop('href',"index.html");
        // $(anchor).click(function(){showResult(this)});
        $(anchor).text(tags_arr[i]);
        $('h5[name=edit_current_keywords]').append(anchor);
    }

}

function save_keywords_clicked(){

    var tags_arr = [];

    $('#edit_keywords').prop('style','display:inline-block;');
    $('#save_keywords').prop('style','display:none;');
    
    $("input.edited_keyword").each(function(){
        if($(this).val()){
            tags_arr.push($(this).val());
        }
    });

    console.log(tags_arr);
    search_link = $('#search_link').val();
    if(tags_arr.length>0){
        $.ajax({
            type:'POST',
            url:search_link,
            data:{
                keyword: tags_arr.join(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(response){
                console.log(response);
                location.reload(true);
            },
            error:function(){
                alert('Error');
            }
        });
    }
}

function send_keywords(){
    var tags_arr = [];

    $(".keywords > a").each(function(){
        if($(this).text()){
            tags_arr.push($(this).text());
        }
    });

    console.log(tags_arr);

    $("div.new_tags").each(function(){
        if($(this).text()){
            tags_arr.push($(this).text());
        }
    });

    console.log(tags_arr);

    console.log(tags_arr.join());
    search_link = $('#search_link').val();
    if(tags_arr.length>0){
        $.ajax({
            type:'POST',
            url:search_link,
            data:{
                keyword: tags_arr.join(),
                csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
            },
            success:function(response){
                console.log(response);
                location.reload(true);
            },
            error:function(){
                alert('Error');
            }
        });
    }
}
    

function cancelDiv(ele){
    console.log($($(ele).parent()).remove());
}
 */