$(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('photoGallery'));
    if (rowElements !== null){
        localStorage.setItem('oldPhotoStorage', JSON.stringify(rowElements));
        let photoRow = $(".photos .row");
        photoRow.html('');
        for (let i = 0; i < rowElements.length; i++){
            photoRow.append(`<div class='col-md-4'>`+rowElements[i]+`</div>`);
        }
    }

    /**
     * Cache block with it's inputs values when change input
     * it's useful when validation return any errors
     */
    $(document).on('change', '.photos .row input[type="text"]', function () {
        $(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('photoGallery', JSON.stringify(appendArray));
    }

});
