$(document).ready(function () {

    /**
     * check local storage appendArray key if null or not
     * to get it's contain to append it to photo row block
     * this key store old image block in local storage
     * to show it again when validation error
     */

    let rowElements = JSON.parse(localStorage.getItem('websiteGalleryPhoto')),
        width = localStorage.getItem('width') ? localStorage.getItem('width') : 'col-md-6';
    if (rowElements !== null){
        localStorage.setItem('oldWebsiteGalleryPhoto', JSON.stringify(rowElements));
        let photoRow = $(".photos .row");
        photoRow.html('');
        for (let i = 0; i < rowElements.length; i++){
            photoRow.append(`<div class='`+width+`'>`+rowElements[i]+`</div>`);
        }
    }

    /**
     * Cache block with it's inputs values when change input
     */
    $(document).on('change', '.photos .row input[type="text"]', function () {
        let appendArray = [];
        $(this).attr('value', $(this).val());
        rebuildLocalStorage();
    });

    /**
     * to reset inputs in image lock when
     * delete it by close button
     */
    $(document).on('click', 'a.close', function () {
        $(this).parent('.items').parent('div').remove();
        rebuildLocalStorage();
    });

    function rebuildLocalStorage() {
        let appendArray = [];
        $(".photos .row").children('.row > div').each(function () {
            appendArray.push($(this).html());
        });
        localStorage.setItem('websiteGalleryPhoto', JSON.stringify(appendArray));
    }

});
