@push('head_links')
<style>
    /* Media library modal styles */
    /* -------------------------- */
    #media_library_modal {
        bottom: initial !important; /* dozvoljava rad izvan modala */
    }

    #media_library_modal .modal-dialog {
        /*min-width: 80%;*/
        width: calc(100% - 30px) !important;
        max-width: 1400px !important;
        /*height: 92%;*/
        padding: 0;
    }
    
    #media_library_modal .modal-header {
        background-color: #4a4a4a;
        padding-left: 1rem;
        border-bottom: 4px solid #949494;
        cursor: grabbing;
    }

    #media_library_modal .modal-header .modal-title {
        padding-top: 0.3rem;
        color: #f3f3f3;
    }

    #media_library_modal .modal-header button > span {
        opacity: 1;
    }

    #media_library_modal .modal-header button > span {
        color: white !important;
        text-shadow: none;
    }

    #media_library_modal .modal-header .close {
        margin-top: -0.1rem;
        margin-right: 0.3rem;
    }

    #media_library_modal .modal-content {
        padding: 0;
        height: 99%;
       /* border: 1px solid #313a46;*/
        border: 1px solid #949494;
        border-radius: 6px;
    }

    #media_library_modal .modal-body {
        padding-top: 0; 
        padding-left: 1rem;
        padding-right: 1rem;
        height: 100vh;
        max-height: calc(100vh - 7rem);
        overflow-y: scroll;
    }
    
    #media_library_modal .nav-tabs li a.active {
        border-bottom: 3px solid #FFF100;
    }

    #media_library_modal .tab-content .card {
        box-shadow: none;
    }

    #media_library_modal .container-fluid {
        padding-left: 0;
        padding-right: 0;
    }

    /* styles for all tabs */
    #media_library_modal .inputs-wrapper .card {
        background-color: #fafafa;
    }

    #media_library_modal .inputs-wrapper .card-body {
        padding-bottom: 0.6rem;
    }

    #media_library_modal .select2-selection__placeholder {
        color: #dee2e6 !important;
    }

    .datatable-toolbar {
        flex-wrap: wrap;
    }

    .datatable-toolbar > * {
        margin-bottom: 5px;
    }

    .datatable-toolbar .dt-buttons {
        height: auto !important;
    }

    .action-buttons-wrapper[data-v-18af2a3f] {
        margin-bottom: 20px;
    }

    div[data-v-46739d03] .btn-secondary {
        display: none;
    }

    #create-form .select2-container--default .select2-selection--multiple .select2-selection__choice {
        float: none;
    }
    #create-form .select2-container .select2-selection--multiple .select2-selection__rendered {
        white-space: normal;
    }
</style>
<link href="https://cdn.datatables.net/buttons/1.6.3/css/buttons.bootstrap4.min.css" rel="stylesheet" type="text/css"/>
<link href="{{ asset('theme/plugins/jquery-ui/jquery-ui.min.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('custom/js/plupload-3.1.2/js/jquery.plupload.queue/css/jquery.plupload.queue.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('custom/cropperjs/cropper.min.css') }}" rel="stylesheet" type="text/css"/>
@endpush

<div class="modal" id="media_library_modal" tabindex="-1" role="dialog" data-backdrop="false"> <!-- data-keyboard="false" -->
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">@lang('Menadžer fotografija')</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div role="tabpanel">
                    <!-- Nav tabs -->
                    <ul class="nav nav-tabs" role="tablist">
                        <li role="presentation" class="active" id="tablist_search_tab">
                            <a href="#search_tab" aria-controls="search_tab" role="tab" data-toggle="tab">
                                <i class="mdi mdi-magnify"></i> @lang('Pretraga')
                            </a>
                        </li>
                        <li role="presentation" id="tablist_upload_tab">
                            <a href="#upload_tab" aria-controls="upload_tab" role="tab" data-toggle="tab">
                                <i class="mdi mdi-upload"></i> @lang('Kreiranje')
                            </a>
                        </li>
                        <li role="presentation" class="d-none" id="tablist_edit_tab">
                            <a href="#edit_tab" aria-controls="edit_tab" role="tab" data-toggle="tab">
                                <i class="mdi mdi-pencil"></i> @lang('Izmena')
                            </a>
                        </li>
                        <li role="presentation" class="d-none" id="tablist_select_photo_tab">
                            <a href="#select_photo_tab" aria-controls="select_photo_tab" role="tab" data-toggle="tab">
                                <i class="mdi mdi-image-album"></i> @lang('Selekcija fotografije')
                            </a>
                        </li>
                        <li role="presentation" class="d-none" id="tablist_photo_gallery_tab">
                            <a href="#photo_gallery_tab" aria-controls="photo_gallery_tab" role="tab" data-toggle="tab">
                                <i class="mdi mdi-image-frame"></i> @lang('Foto galerija')
                            </a>
                        </li>
                    </ul>
                    <!-- Tab panes -->
                    <div class="tab-content">
                        <div role="tabpanel" class="tab-pane active" id="search_tab">
                            <ml-search-tab 
                                ref="searchTabComponent"
                                v-bind:trans="view.searchTab.trans"
                                v-bind:categories-list="view.categoriesList" 
                                v-bind:licences-list="view.licencesList" 
                                v-bind:dateranges="view.searchTab.dateranges"
                                v-bind:start-date="state.searchTab.startDate"
                                v-bind:end-date="state.searchTab.endDate"
                                v-bind:datatable-thumb-sizes="view.mediaThumbs"
                                datatable-ajax-url="{{ route('media.library.datatable') }}"
                                v-bind:datatable-initial-thumb-id="initialThumbId"
                                v-bind:datatable-initial-thumb-name="initialThumbName"
                                v-bind:thumb-size-id-storage-key="view.searchTab.thumbSizeIdStorageKey"
                                v-bind:thumb-size-name-storage-key="view.searchTab.thumbSizeNameStorageKey"
                                tags-source-url="{{ route('tags.select_tag') }}"
                                tags-store-url="{{ route('tags.create_tag') }}"
                                tags-value-url="{{ route('tags.fetch_tags') }}"
                                source-ajax-url="{{ route('media.sources.autocomplete') }}"
                                v-bind:insert-button-disabled="state.insertButtonDisabled"
                                v-bind:insert-buttons-text="insertButtonsText"
                                v-on:photo-edit="onPhotoEdit"
                                v-on:photo-dbl-click="onPhotoDblClick"
                                v-on:insert-save="onInsertSave"
                                v-on:insert-cancel="onInsertCancel"
                                >
                            </ml-search-tab>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="upload_tab">
                            <ml-upload-tab 
                                v-bind:trans="view.uploadTab.trans"
                                v-bind:categories-list="view.categoriesList" 
                                v-bind:licences-list="view.licencesList" 
                                upload-url="{{ route('media.library.upload') }}" 
                                source-url="{{ route('media.sources.autocomplete') }}" 
                                source-placeholder="@lang('Unesite autora')" 
                                tags-source-url="{{ route('tags.select_tag') }}" 
                                tags-store-url="{{ route('tags.create_tag') }}" 
                                tags-value-url="{{ route('tags.fetch_tags') }}"
                                get-image-data-ajax-url="{{ route('media.library.get_image_data') }}"
                                v-bind:upload-metadata="state.uploadTab"
                                v-on:photo-edit="onPhotoEdit"
                                v-on:photo-dbl-click="onPhotoDblClick"
                            >
                            </ml-upload-tab>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="edit_tab">
                            <ml-edit-tab 
                                ref="editTabComponent"
                                v-bind:trans="view.editTab.trans"
                                v-bind:active-image-obj="state.active.imageObj"
                                v-bind:thumb-sizes="view.mediaThumbs"
                                v-bind:categories-list="view.categoriesList" 
                                v-bind:licences-list="view.licencesList" 
                                tags-source-url="{{ route('tags.select_tag') }}"
                                tags-store-url="{{ route('tags.create_tag') }}"
                                tags-value-url="{{ route('tags.fetch_tags') }}"
                                source-ajax-url="{{ route('media.sources.autocomplete') }}"
                                update-ajax-url="{{ route('media.library.update') }}"
                                v-bind:insert-button-disabled="state.insertButtonDisabled"
                                v-bind:insert-buttons-text="insertButtonsText"
                                v-on:insert-save="onInsertSave"
                                v-on:insert-cancel="onInsertCancel"
                                v-on:edit-photo-thumb-changed="onEditPhotoThumbChange"
                                >
                            </ml-edit-tab>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="select_photo_tab">
                            <ml-select-photo-tab 
                                v-bind:trans="view.selectPhotoTab.trans"
                                v-bind:thumb-sizes="view.mediaThumbs"
                                v-bind:thumb-size-id="state.active.imageObj.photoThumbSizeId"
                                v-bind:filename="state.active.imageObj.photoFilename"
                                v-bind:img-src="state.active.imageObj.photoImgSrc"
                                v-bind:selection.sync="state.active.selection"
                                v-bind:insert-button-disabled="state.insertButtonDisabled"
                                v-on:selection-img-size-changed="onSelectionImgSizeChange"
                                v-on:insert-save="onInsertSave"
                                v-on:insert-cancel="onInsertCancel"
                                >
                            </ml-select-photo-tab>
                        </div>
                        <div role="tabpanel" class="tab-pane" id="photo_gallery_tab">
                            <ml-photo-gallery-tab 
                                ref="galleryTabComponent"
                                v-bind:trans="view.photoGalleryTab.trans"
                                v-bind:gallery-id="state.photoGalleryTab.galleryId"
                                v-bind:gallery-items="[]"
                                v-bind:insert-button-disabled="state.insertButtonDisabled"
                                create-gallery-ajax-url="{{ route('media.gallery.create') }}"
                                update-gallery-ajax-url="{{ route('media.gallery.update') }}"
                                v-on:insert-button-disabled="onInsertButtonDisabled"
                                v-on:insert-save="onInsertSave"
                                v-on:insert-cancel="onInsertCancel"
                                >
                            </ml-photo-gallery-tab>
                        </div>
                    </div>
                </div> <!-- ./role="tabpanel" -->
            </div> <!-- ./modal-body -->
        </div> <!-- ./modal-content -->
    </div> <!-- ./modal-dialog -->
</div> <!-- ./modal -->

@push('footer_scripts')
<script src="{{ asset('custom/js/plupload-3.1.2/js/plupload.full.min.js') }}"></script>
{{-- <script src="{{ asset('custom/js/plupload-3.1.2/js/jquery.plupload.queue/jquery.plupload.queue.min.js') }}"></script> --}}
<script src="{{ asset('custom/js/plupload-3.1.2/js/jquery.plupload.queue/jquery.plupload.queue.js') }}"></script>

<script src="{{ asset('custom/js/plupload-3.1.2/js/i18n/' . app()->getLocale() . '.js') }}"></script>
<script src="{{ asset('js/app.js' )}}?v=2"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.6.3/js/buttons.bootstrap4.min.js"></script>
<script src="{{ asset('custom/cropperjs/cropper.min.js') }}"></script>
<script>
    var mlBlade = {
        categoriesList: {!! \App\Models\MediaCategory::getSelect2SpecData(['id' => 'id', 'text' => 'category']) !!},
        licencesList: {!! \App\Models\MediaLicence::getSelect2SpecData(['id' => 'id', 'text' => 'description']) !!},
        mediaThumbs: {!! json_encode(config('media.thumbs')) !!},
        forSearchTab: {
            trans: {
                filtersTitle: "@lang('Filteri')",
                filtersSubtitle: "@lang('Filteri fotografija')",
                filterCategory: "@lang('Kategorija')",
                filterLicence: "@lang('Licenca')",
                filterTags: "@lang('Tagovi')",
                filterFilename: "@lang('Ime fajla')",
                filterSource: "@lang('Autor')",
                filterCreatedAt: "@lang('Kreirano')",
                filterCategoryPlaceholder: "@lang('Izaberite kategoriju')",
                filterLicencePlaceholder: "@lang('Izaberite licencu')",
                filterSourcePlaceholder: "@lang('Unesite autora')",
                filterFilenamePlaceholder: "@lang('Ime fajla')",
                allCategories: "@lang('Sve Kategorije')",
                allLicences: "@lang('Sve Licence')",
                search: "@lang('Pretraži')",
                reset: "@lang('Resetuj')",
                table: {
                    lmSuffix: "@lang('fotografija')",
                    zeroRecords: "@lang('Nije pronađena nijedna fotografija')"
                },
                insertPhotoButtons: {
                    save: "@lang('Ubaci')",
                    cancel: "@lang('Otkaži')",
                }
            },
            defaultThumbId: "{{ config('media.library_settings.search_default_thumb_id') }}",
            defaultThumbName: "{{ config('media.library_settings.search_default_thumb_name') }}",
            defautStartDate: "{{ config('media.library_settings.search_default_start_date', now()->addYears(-2)) }}",
            defaultEndDate: "{{ now() }}",
            dateranges: {
                "@lang('Tekući mesec')": [
                    moment('{{ now()->startOfMonth() }}'), 
                    moment('{{ now() }}')
                ],
                "@lang('Od prethodnog meseca')": [
                    moment('{{ now()->add(-1, "month")->startOfMonth() }}'),
                    moment('{{ now() }}')
                ],
                "@lang('Od pre 2 meseca')": [
                    moment('{{ now()->add(-2, "month")->startOfMonth()}}'),
                    moment('{{ now() }}')
                ],
                "@lang('Od pre 6 meseci')": [
                    moment('{{ now()->add(-6, "month")->startOfMonth() }}'),
                    moment('{{ now() }}')
                ],
                "@lang('Od pre godinu dana')": [
                    moment('{{ now()->add(-1, "year") }}'),
                    moment('{{ now() }}')
                ],
                "@lang('Od pre dve godine')": [
                    moment('{{ now()->add(-2, "year") }}'),
                    moment('{{ now() }}')
                ]
            }
        },
        forUploadTab: {
            trans: {
                infoSubsection: "@lang('Informacije')",
                infoSubsectionSubtitle: "@lang('Metapodaci vezani za fotografiju')",
                category: "@lang('Kategorija')",
                licence: "@lang('Licenca')",
                source: "@lang('Autor')",
                tags: "@lang('Tagovi')",
                tagsMinimum: "@lang('najmanje 2')",
                uploadPhotos: "@lang('Otpremite slike')",
                noSupport: "@lang('Vaš pretraživač ne podržava Flash, Silverlight ili HTML5.')",
                setUploadDataError: "@lang('Došlo je do greške prilikom pokušaja setovanja meta podataka \"upload\"-a')",
                reset: "@lang('Resetuj')",
            }
        },
        forEditTab: {
            trans: {
                thumbnailsSubsection: "@lang('Veličina')",
                propertiesSubsection: "@lang('Osobine')",
                infoSubsection: "@lang('Dodatne informacije')",
                thumbSize: "@lang('Foto veličina ')",
                category: "@lang('Kategorija')",
                licence: "@lang('Licenca')",
                tags: "@lang('Tagovi')",
                source: "@lang('Autor')",
                signature: "@lang('Potpis')",
                created: "@lang('Kreirana')",
                modified: "@lang('Modifikovana')",
                categoryPlaceholder: "@lang('Izaberite kategoriju')",
                licencePlaceholder: "@lang('Izaberite licencu')",
                fetchPhotoError: "@lang('Došlo je do greške prilikom preuzimanja podataka fotografije')",
                propertiesButtons: {
                    save: "@lang('Snimi')",
                    select: "@lang('Selektuj')",
                    cancel: "@lang('Odbaci')",
                },
                insertPhotoButtons: {
                    save: "@lang('Ubaci')",
                    cancel: "@lang('Otkaži')",
                }
            }
        },
        forSelectPhotoTab: {
            trans: {
                change: "@lang('Odaberi')",
                edit: "@lang('Izmeni')",
                thumbSize: "@lang('Veličina fotografije')",
                position: "@lang('Pozicija fotografije')",
                positionLeft: "@lang('levo')",
                positionCenter: "@lang('centar')",
                positionRight: "@lang('desno')",
                signature: "@lang('Ubaci potpis')",
                fetchPhotoError: "@lang('Došlo je do greške prilikom preuzimanja podataka fotografije')",
                insertPhotoButtons: {
                    save: "@lang('Ubaci')",
                    cancel: "@lang('Otkaži')",
                }
            },
            getImageDataAjaxUrl: "{{ route('media.library.get_image_data') }}"
        },
        forPhotoGalleryTab: {
            trans: {
                embedCode: "@lang('Ubaci \"embed code\"')",
                addPhoto: "@lang('Dodaj Fotografije')",
                galleryNamePlaceholder: "@lang('Naziv galerije')",
                photoAlreadyExistsInGallery: "@lang('Fotografija već postoji u galeriji')",
                photoAddedToGallery: "@lang('Fotografija je pridružena galeriji')",
                embedCodeAddedToGallery: "@lang('\"embed code\" je pridružen galeriji')",
                embedCodeAlreadyExistsInGallery: "@lang('\"embed code\" već postoji u galeriji')",
                createPhotoAjaxError: "@lang('Došlo je do greške prilikom pokušaja kreiranja unosa galerije fotografija u bazi podataka')",
                fetchGalleryError: "@lang('Došlo je do greške prilikom uzimanja podataka galerije fotografija iz baze podataka')",
                embedCodePopup: {
                    title: "@lang('Embed Code')",
                    btnConfirm: "@lang('Ubaci')",
                    btnCancel: "@lang('Poništi')"
                },
                galleryItem: {
                    description: "@lang('Opis')"
                },
                insertPhotoButtons: {
                    save: "@lang('Snimi Galeriju')",
                    cancel: "@lang('Otkaži')",
                }
            },
            getGalleryDataAjaxUrl: "{{ route('media.gallery.get_gallery_data') }}",
        }
    };

    /**
     * Konstruktorska funkcija za MediaLibrary
     * 
     * @param String tab
     * @return void 
     */
    function MediaLibrary(tab) {

        let openModalOnInit = false;

        if(typeof tab !== 'undefined') {
            let allowedInitTabs = ['search_tab', 'upload_tab'];
            if( ! _.includes(allowedInitTabs, tab) ) {
                    console.error('MediaLibrary Error: tab argument in MediaLibrary ' +
                                  'constructor must be one of: ' + allowedInitTabs);
                    return false;
            }
            openModalOnInit = true;
        }

        if (!(this instanceof MediaLibrary)) {
            return new MediaLibrary(tab);
        }

        if(typeof window._mediaLibraryVm === 'undefined') {
            window._mediaLibraryVm = this._createVm();
            this._makeModalDraggable();
        }

        this._selectModalTab(tab);

        if(openModalOnInit) {
            this.modalShow();
        }

        return this;
    }

    /**
     * Kreiraj Vue js objekat.
     * 
     * @return Object
     */
    MediaLibrary.prototype._createVm = function() {

        return new Vue({
            el: '#media_library_modal .modal-body',
            data: {
                state: {
                    searchTab: {
                        startDate: mlBlade.forSearchTab.defautStartDate,
                        endDate: mlBlade.forSearchTab.defaultEndDate,
                        onPhotoClickCallback: null
                    },
                    uploadTab: {
                        category: null,
                        licence: null,
                        source: '',
                        //tags: [],
                        tagIds: [],
                    },
                    editTab: {},
                    selectPhotoTab: {
                        onInsertCallback: (imageObj, thumbId, position, signature) => {
                            console.log("mediaLibrary default on insert callback");
                            let data = {
                                "imageObj": imageObj,
                                "thumbId": thumbId,
                                "position": position,
                                "signature": signature
                            };
                            let eventData = {type:"insert.media-library", "mediaLibraryData": data}
                            $('#media_library_modal').trigger(eventData);
                            console.log("Raised event insert.media-library with mediaLibraryData:");
                            console.log(data);
                        }
                    },
                    photoGalleryTab: {
                        galleryId: null,
                        onInsertCallback: (galleryTitle, galleryItems) => {
                            console.log("mediaLibrary default on insert gallery callback");
                            console.log("gallery title = " + galleryTitle);
                            console.log("Gallery items:");
                            console.log(galleryItems);
                        }
                    },
                    mode: 'sp', // 'sp' -> ulazi u 'select photo' na klik fotografije, 'pg' -> ulazi u 'photo gallery'
                    insertButtonDisabled: false,
                    active: {
                        imageObj: {
                            photoThumbSizeId: '',
                            photoFilename: '',
                            photoImgSrc: ''
                        },
                        selection: {
                            thumbSizeId: '',
                            position: 'center',
                            showSignature: false,
                            signature: ''
                        },
                        datatableReload: true,
                        cropperReload: false
                    }
                },
                view: {
                    categoriesList: mlBlade.categoriesList,
                    licencesList: mlBlade.licencesList,
                    mediaThumbs: mlBlade.mediaThumbs,
                    searchTab: {
                        trans: mlBlade.forSearchTab.trans,
                        dateranges: mlBlade.forSearchTab.dateranges,
                        thumbSizeIdStorageKey: 'mediaLibrary.default_thumb_size_id',
                        thumbSizeNameStorageKey: 'mediaLibrary.default_thumb_size_name',
                    },
                    uploadTab: {
                        trans: mlBlade.forUploadTab.trans
                    },
                    editTab: {
                        trans: mlBlade.forEditTab.trans,
                    },
                    selectPhotoTab: {
                        trans: mlBlade.forSelectPhotoTab.trans
                    },
                    photoGalleryTab: {
                        trans: mlBlade.forPhotoGalleryTab.trans
                    }
                }
            },
            computed: {
                initialThumbId() {
                    return localStorage.getItem(this.view.searchTab.thumbSizeIdStorageKey) 
                                ? localStorage.getItem(this.view.searchTab.thumbSizeIdStorageKey) 
                                : mlBlade.forSearchTab.defaultThumbId;
                },
                initialThumbName() {
                    return localStorage.getItem(this.view.searchTab.thumbSizeNameStorageKey) 
                                ? localStorage.getItem(this.view.searchTab.thumbSizeNameStorageKey) 
                                : mlBlade.forSearchTab.defaultThumbName;
                },
                insertButtonsText() {
                    /*
                    if(this.state.mode == 'pg') {
                        return mlBlade.forPhotoGalleryTab.trans.insertPhotoButons;
                    }
                    else {
                        return mlBlade.forSelectPhotoTab.trans.insertPhotoButtons;
                    }
                    */ // ???? <- [Vue warn]: Error in render: "TypeError: _vm.trans is undefined"
                    if(this.state.mode == 'pg') {
                        return {
                            save: "@lang('Snimi galeriju')",
                            cancel: "@lang('Otkaži')"
                        };
                    }
                    else {
                        return {
                            save: "@lang('Ubaci')",
                            cancel: "@lang('Otkaži')"
                        };
                    }
                }
            },
            methods: {
                /* 
                * Otvori trazeni tab.
                */
                openTab(tab) {
                    $('#tablist_' + tab).removeClass('d-none');
                    $('#media_library_modal .nav-tabs a[href="#' + tab + '"]').tab('show');
                },
                /**
                 * Vrati putanju do slike zeljene velicine.
                 */
                getImgThumbSrc(thumbSizeId) {
                    if(this.state.active.imageObj.photoAllImgSources && 
                        this.state.active.imageObj.photoAllImgSources[thumbSizeId]) {
                        return this.state.active.imageObj.photoAllImgSources[thumbSizeId];
                    }
                    let imgSrcTemplate = this.state.active.imageObj.photoImgSrcTemplate;
                    let placeholder = this.state.active.imageObj.photoTemplatePlaceholder;
                    let imgSrcPath = imgSrcTemplate.replace(placeholder, thumbSizeId);
                    return imgSrcPath;
                },
                /**
                 * Setuj inicijalne podatke na upload tabu.
                 */
                uploadTabSetData(data, successCallback, errorCallback) {
                    this.state.uploadTab = _.merge(this.state.uploadTab, data);
                    successCallback(); 
                },
                /**
                 * Setuj inicijalne podatke na edit tabu.
                 */
                editTabSetData(data, successCallback, errorCallback) {

                    $.ajax({
                        url: mlBlade.forSelectPhotoTab.getImageDataAjaxUrl,
                        type: 'POST',
                        data: { 
                            'photo_id': data.photoId,
                            'thumb_id': data.thumbSizeId 
                        },
                    }).done((res) => {
                        if(res && res.status == 'ok' && res.data) {
                            this.state.active.imageObj = res.data;
                            successCallback();
                        }
                    }).fail((err) => {
                        console.error("Media Library: selectPhotoTabSetData() AJAX ERROR! "); 
                        console.error(err);
                        errorCallback(err);
                    });
                },
                /**
                 * Dobavi podatke slike preko ajaksa i setuj podatke selekcije.
                 */
                selectPhotoTabSetData(selection, successCallback, errorCallback) {

                    $.ajax({
                        url: mlBlade.forSelectPhotoTab.getImageDataAjaxUrl,
                        type: 'POST',
                        data: { 
                            'photo_id': selection.photoId,
                            'thumb_id': selection.thumbSizeId 
                        },
                    }).done((res) => {
                        if(res && res.status == 'ok' && res.data) {
                            this.state.active.imageObj = res.data;

                            let signatureNotEmpty;

                            // if (res.data.photoSignature != 'null') {
                            //     selection.signature = res.data.photoSignature;
                            // } else {
                            //     selection.signature = "";
                            // }
                            

                            if(selection.signature == "" || selection.signature == "\n"){
                                signatureNotEmpty = false;
                            }else{
                                signatureNotEmpty = true;
                            }
                            this.state.active.selection = _.merge(this.state.active.selection, selection);
                            this.state.active.selection.showSignature = signatureNotEmpty;

                            successCallback();
                        }
                    }).fail((err) => {
                        console.error("Media Library: selectPhotoTabSetData() AJAX ERROR! "); 
                        console.error(err);
                        errorCallback(err);
                    });
                },
                /**
                 * Uzmi podatke galerije preko ajaksa i popuni galeriju.
                 */
                loadGallery(galleryId, successCallback, errorCallback) {
                    $.ajax({
                        url: mlBlade.forPhotoGalleryTab.getGalleryDataAjaxUrl,
                        type: 'POST',
                        data: { 
                            'gallery_id': galleryId
                        },
                    }).done((res) => {
                        if(res && res.status == 'ok' && res.data) {
                            let galleryItems = (typeof(res.data.items) === 'string' ? JSON.parse(res.data.items) : res.data.items);
                            this.$refs.galleryTabComponent.state.gallery_items = galleryItems;
                            this.$refs.galleryTabComponent.state.gallery_title = res.data.title;
                            successCallback();
                        }
                    }).fail((err) => {
                        console.error("Media Library: loadGallery() AJAX ERROR! "); 
                        console.error(err);
                        errorCallback(err);
                    });
                },
                /**
                 * Funkcija koja se poziva kada se dogodi 'insert-save event'.
                 */
                onInsertSave(data) {
                    if(this.state.mode == 'sp') {
                        this.onInsertPhoto();
                    }
                    else if(this.state.mode == 'pg') {
                        this.onInsertGallery(data);
                    }
                },
                /**
                 * Funkcija koja se poziva kada treba da se ubaci fotografija.
                 */
                onInsertPhoto() {
                    this.state.selectPhotoTab.onInsertCallback(
                        this.state.active.imageObj,
                        this.state.active.selection.thumbSizeId,
                        this.state.active.selection.position,
                        this.state.active.selection.signature
                    );
                },
                /**
                 * Funkcija koja se poziva kada treba da se ubaci galerija.
                 */
                onInsertGallery(data) {
                    this.state.photoGalleryTab.onInsertCallback(
                        data.gallery_id,
                        data.gallery_title,
                        data.gallery_items
                    );
                },
                /**
                 * Funkcija koja se poziva kada se dogodi 'insert-cancel event'.
                 */
                onInsertCancel() {
                    $('#media_library_modal').modal('hide');
                },
                /**
                 * Funkcija koja se poziva kada se promeni velicina slike na
                 * 'selectPhoto' tabu (kada se desi 'selection-img-size-changed event').
                 */
                onSelectionImgSizeChange(data) {
                    this.state.active.imageObj.photoImgSrc = data.img_src;
                    this.state.active.imageObj.photoThumbSizeId = data.thumb_size_id;
                },
                /**
                 * Funkcija koja treba da se poziva kada je 'media library' u 'pg (photo gallery)' rezimu.
                 */
                modePhotoGalleryOnShow(imageObj) {
                    this.$refs.galleryTabComponent.addGalleryPhotoItem(imageObj);
                    // ostavljamo korisniku da sam prebaci na 'gallery tab'
                },
                /**
                 * Funkcija koja treba da se poziva kada je 'media library' pokrenut na indeksnoj stranici ('mli' rezim).
                 */
                modeMediaLibraryIndexOnShow(imageObj) {
                    if(this.state.searchTab.onPhotoClickCallback) {
                        let retVal = this.state.searchTab.onPhotoClickCallback(imageObj);
                        if(retVal === false) {
                            return;
                        }
                    }
                    this.state.active.imageObj = imageObj;
                    this.state.active.cropperReload = true;
                    this.openTab('edit_tab');
                },
                /**
                 * Funkcija koja treba da se poziva kada je 'media library' u 'sp (select photo)' rezimu.
                 */
                modeSelectPhotoOnShow(imageObj) {
                    if(this.state.searchTab.onPhotoClickCallback) {
                        let retVal = this.state.searchTab.onPhotoClickCallback(imageObj);
                        if(retVal === false) {
                            return;
                        }
                    }
                    this.state.active.cropperReload = true;
                    this.openTab('select_photo_tab');
                },
                onPhotoDblClick(imageObj) {
                    this.state.active.imageObj = imageObj;

                    if(this.state.mode == 'sp') {
                        this.modeSelectPhotoOnShow(imageObj);
                    }
                    else if(this.state.mode == 'pg') {
                        this.modePhotoGalleryOnShow(imageObj);
                    }
                    else if(this.state.mode == 'mli') {
                        this.modeMediaLibraryIndexOnShow(imageObj);
                    }
                    else {
                        throw 'Media Library: Programmer error. Invalid media library mode set.';
                    }
                },
                onPhotoEdit(imageObj) {
                    if(this.state.mode == 'mli') {
                        this.modeMediaLibraryIndexOnShow(imageObj);
                    }
                    else {
                        this.state.active.imageObj = imageObj;
                        this.state.active.cropperReload = true;
                        this.openTab('edit_tab');
                    }
                },
                onEditPhotoThumbChange(data) {
                    let eventData = {type:"edit-photo-thumb-changed.media-library", "mediaLibraryData": data};
                    $('#media_library_modal').trigger(eventData);
                },
                onInsertButtonDisabled(val) {
                    if(this.state.mode == 'pg') { 
                        this.state.insertButtonDisabled = val;
                    }
                }
            },
            mounted() {
                $('a[data-toggle="tab"]').on('shown.bs.tab', (e) => {

                    let activeTabId = $(e.target).attr("href");

                    if(activeTabId == '#search_tab') {
                        // uradi 'refresh search datatable'-a samo ukoliko je 
                        // ucinjena neka izmena kod 'edit'-a ili je izvrsen 'upload'.
                        if(this.state.active.datatableReload === true) { 
                            this.state.active.datatableReload = false;
                            this.$refs.searchTabComponent.refreshDatatable(false); 
                        }
                    }
                    else if(activeTabId == '#edit_tab') {
                        //if(this.state.active.cropperReload === true) {  <- neuspesno

                        // ukoliko se stavi '$nextTick' onda se ne prikazuje 'preview' slika na edit tabu
                        setTimeout(() => {
                            this.state.active.cropperReload = false;
                            this.$refs.editTabComponent.initCropper(); 
                        }, 100);
                    }
                });
            }
        });

    };

    /**
     * Izracunaj dimenzije 'containment' kvadrata koje sluze kao ogranicenje za
     * 'draggable'.
     */
    MediaLibrary.prototype._getContainmentDim = function() {
        let modalWidth = Number($('#media_library_modal .modal-dialog').css('min-width')    
                                                                        .replace(/px$/, ''));
        //let body = document.body, html = document.documentElement;
        //let height = Math.max( body.scrollHeight, body.offsetHeight, 
        //                       html.clientHeight, html.scrollHeight, html.offsetHeight );
        //height = window.screen.availHeight;

        let st = document.documentElement.scrollTop;

        return [-(window.screen.availWidth - modalWidth), st -30,
                window.screen.availWidth - modalWidth, st + window.screen.availHeight - 150];
    };

    /**
     * Ucini modal 'draggable'-nim
     */
    MediaLibrary.prototype._makeModalDraggable = function() {

        // setuj modal da bude "draggable" kao prozor.
        $("#media_library_modal").draggable({
            handle: ".modal-header",
            cursor: "grab",
            containment: this._getContainmentDim(), //$('div.content-page .container-fluid'), <- Odbija, zbaguje se !!!
            scroll: false
        });
    };

    /**
     * Selektuj trazeni tab
     */
    MediaLibrary.prototype._selectModalTab = function(tab) {
        let defaultTab = 'search_tab';
        let allTabs = [];

        _.forEach($('#media_library_modal .tab-content > .tab-pane'), (item, key) => {
            allTabs.push($(item).attr('id'));
        });

        if( ! _.includes(allTabs, tab) ) {
            tab = defaultTab;
        }

        window._mediaLibraryVm.openTab(tab);
    };

    /**
     * Validiraj elemente objekta.
     */
    MediaLibrary.prototype._validateFields = function(obj, validations) {
        let errors = [];

        _.forOwn(validations, function(validator, key) { 

            if(validator.hasOwnProperty('required') && validator.required && ! obj.hasOwnProperty(key)) {
                errors.push(key + ' field is required');
            }
            if(validator.hasOwnProperty('filled') && validator.filled && obj.hasOwnProperty(key) && _.isNumber(obj[key])) {
                // skip --> ovo proverava da li je vrednost broj (_.isEmpty() ne proverava tu situaciju).
            }
            else if(validator.hasOwnProperty('filled') && validator.filled && obj.hasOwnProperty(key) && _.isEmpty(obj[key])) {
                errors.push(key + ' field must be filled');
            }
            if(validator.hasOwnProperty('valueIn') && obj.hasOwnProperty(key) && ! _.includes(validator.valueIn, obj[key]) ) {
                errors.push(key + ' field value must be one of = ' + validator.valueIn);
            }
            if(validator.hasOwnProperty('mustAbide') && obj.hasOwnProperty(key)) {
                let msg = validator.mustAbide(obj[key]);
                if(msg !== true) {
                    errors.push(key + ' field invalid. ' + msg);
                }
            }

        });

        if(errors.length > 0) {
            return errors;
        }

        return true;
    };

    /**
     * Validiraj 'selection' objekat. Mora biti u formatu:
     * 
     *     {
     *          photoId: 2,
     *          thumbId: 'f',
     *          position: 'center',
     *          signature: 'Ovo je jedna fotografija"'
     *     };  
     */
    MediaLibrary.prototype._validateSelectionObject = function(selection) {
        if(typeof selection !== 'object') {
            console.error('MediaLibrary Error: selection argument must be of Object type.');
            return false;
        }

        let validated = this._validateFields(selection, { 
            photoId: {required: true, filled: true, mustAbide: (val) => {
                    return _.isNumber(val) ? true : 'Field must be a number'
                }
            },
            thumbSizeId: {required: true, filled: true, valueIn: _.map(mlBlade.mediaThumbs, 'id')},
            position: {required: true, filled: true, valueIn: ['left', 'center', 'right']},
            signature: {required: false, filled: true},
        });

        if(validated !== true) {
            console.error("MediaLibrary Error: received selection object format invalid. Errors:");
            console.error(validated);
            return false;
        }
        return true;
    };

    /**
     * Validiraj 'configuration' objekat. Mora biti u formatu:
     * 
     *     {
     *          categoryId: 2,
     *          source: 'Instagram',
     *          tagsIds: [3,6,7]
     *     };  
     */
    MediaLibrary.prototype._validateConfigurationObject = function(configuration) {
        if(typeof configuration !== 'object') {
            console.error('MediaLibrary Error: configuration argument must be of Object type.');
            return false;
        }
        let validated = this._validateFields(configuration, { 
            categoryId: {filled: true, mustAbide: (val) => {
                    return _.isNumber(val) ? true : 'Field must be a number'
                }
            },
            source: {filled: true},
            tagIds: {filled: true, mustAbide: (arr) => {
                if(!_.isArray(arr)) {
                    return "Field must be an array";
                }
                for(let i=0; i<arr.length; ++i) {
                    if(!_.isNumber(arr[i])) {
                        return "Array at index " + i + " must be a number";
                    }
                }
                return true;
            }}
        });

        if(validated !== true) {
            console.error("MediaLibrary Error: received selection object format invalid. Errors:");
            console.error(validated);
            return false;
        }
        return true;
    };

    /**
     * Setuj 'media library' rezim rada.
     */
    MediaLibrary.prototype._setMode = function(mode) {
        if(mode == 'sp') { // select photo
            window._mediaLibraryVm.state.insertButtonDisabled = false;
            $('#tablist_' + 'photo_gallery_tab').addClass('d-none');
            //$('#tablist_' + 'select_photo_tab').removeClass('d-none');
        }
        else if(mode == 'pg') { // photo gallery
            window._mediaLibraryVm.state.insertButtonDisabled = true;
            $('#tablist_' + 'select_photo_tab').addClass('d-none');
            $('#tablist_' + 'photo_gallery_tab').removeClass('d-none');
        }
        else if(mode == 'mli') { // media library index
            window._mediaLibraryVm.state.insertButtonDisabled = true;
            $('#tablist_' + 'select_photo_tab').addClass('d-none');
            $('#tablist_' + 'photo_gallery_tab').addClass('d-none');
        }
        else {
            throw 'Media Library: _setMode() -> Invalid mode received in _setMode!!!';
        }
        window._mediaLibraryVm.state.mode = mode;
    };

    /**
     * Vrati jQuery objekat modala.
     */
    MediaLibrary.prototype.modal = function() {
        return $('#media_library_modal');
    }

    /**
     * Prikazi modal.
     */
    MediaLibrary.prototype.modalShow = function() {
        $('#media_library_modal').modal('show');
        $('#media_library_modal').draggable( "option", "containment", this._getContainmentDim());
        window._mediaLibraryVm.$refs.editTabComponent.initCropper();
    };

    /**
     * Sakrij modal.
     */
    MediaLibrary.prototype.modalHide = function() {
        $('#media_library_modal').modal('hide');
    };

    /**
     * NE RADI !!!!!
     * Izbrisi instancu 'media library'.
     */
    MediaLibrary.prototype.destroy = function() {
        console.log("Destroing VM instance");
        window._mediaLibraryVm.$remove();
    }

    /**
     * Setuj "insert callback" funkciju.
     */
    MediaLibrary.prototype.setInsertCallback = function(onInsertCallback) {
        if(typeof onInsertCallback === 'function') {
            window._mediaLibraryVm.state.selectPhotoTab.onInsertCallback = onInsertCallback;
        }
        else {
            console.error('MediaLibrary Error: setInsertCallback() -> callback argument must be a valid function callback.');
            return false;
        }
    };

    /**
     * Opciono se prosledjuje handler kada se u search tab-u klikne na fotografiju.
     * Ako je hendler prazan po default-u kada se klikne na sliku otvara se "Select Photo" tab.
     */
    MediaLibrary.prototype.openSearchPhotos = function(onPhotoClickCallback, mode) {
        if(typeof onPhotoClickCallback !== 'undefined') {
            if(typeof onPhotoClickCallback === 'function') {
                window._mediaLibraryVm.state.searchTab.onPhotoClickCallback = onPhotoClickCallback;
                this._selectModalTab('search_tab');

                if(typeof mode === 'undefined') {
                    mode = 'sp';
                }
                else if(['sp', 'mli'].indexOf(mode) === -1) {
                    console.error('MediaLibrary Error: openSearchPhotos() -> mode argument value is invalid.');
                    return false;
                }

                this._setMode(mode);
                this.modalShow();
            }
            else {
                console.error('MediaLibrary Error: openSearchPhotos() -> onPhotoClickCallback argument must be a function callback.');
                return false;
            }
        }
    };

    /**
     * Prosledjuje se konfiguracioni objekat koji popunjava formu, sve je opciono.
     * Format konfiguracionog objekta: {categoryId, source, tagIds}
     */
    MediaLibrary.prototype.openUploadPhotos = function(configuration) {
        if(typeof configuration !== 'undefined') {
            if(this._validateConfigurationObject(configuration) !== true) {
                return false;
            }


            window._mediaLibraryVm.uploadTabSetData(
                configuration,
                () => {
                    this._selectModalTab('upload_tab');
                    this._setMode('sp');
                    this.modalShow();
                }, 
                (err) => {
                    showSystemMessage(mlBlade.forUploadTab.trans.setUploadDataError, 'error');
                }
            );
        }
    };

    /**
     * Otvara se edit tab za odredjenu fotografiju u odredjenoj dimenziji.
     * Ako se ne prosledi dimenzija otvara se prva dostupna dimenzija.
     */
    MediaLibrary.prototype.openEditPhoto = function(photoId, thumbSizeId) {
        if(typeof photoId !== 'number') {
            console.error('MediaLibrary Error: openEditPhoto() -> photoId argument must be of type Number.');
            return false;
        }
        if(typeof thumbSizeId !== 'string') {
            console.error('MediaLibrary Error: openEditPhoto() -> thumbId argument must be of type String.');
            return false;
        }

        this._setMode('sp');

        window._mediaLibraryVm.editTabSetData({
                photoId: photoId,
                thumbId: thumbSizeId
            },
            () => {
                this._selectModalTab('edit_tab');
                this.modalShow();
            }, 
            (err) => {
                showSystemMessage(mlBlade.forEditTab.trans.fetchPhotoError, 'error');
            }
        );
    };

    /*
    apiOpenSelectPhoto(function (photo, thumbId, position, signature) {}, {photoId, thumbId, position, signature})
    //sluzi za otvaranje "Select Photo" tab-a
    //obavezan je hendler koji je prvi argument
    //opcioni je drugi parametar koji je objekat sa prikazanim kljucevima i koji populise formu za selektovanje thumb-a fotografije.
    // Ponasanje:
    // 		slucaj A - prosledjen je samo hendler, nije prosledjen konf objekat
    //			apiOpenSelectPhoto(function() {})
    //			Otvara se "Search Tab", i kada se klikne na sliku tada se prelazi na "SelectPhoto" tab
    //		slucaj B - prosledjen je i hendler i konfiguracioni objekat koji ima photoId!!!
    //			apiOpenSelectPhoto(function () {}, {photoId})
    //			direktno se otvara "Select Photo" tab sa popunjenim vrednostima na formi
    */
    MediaLibrary.prototype.openSelectPhoto = function(onInsertCallback, selection) {
        if(this.setInsertCallback(onInsertCallback) === false) return;

        if(typeof selection !== 'undefined') {
            if(this._validateSelectionObject(selection) !== true) {
                return false;
            }

            window._mediaLibraryVm.selectPhotoTabSetData(selection, 
                () => {
                    this._selectModalTab('select_photo_tab');
                    this.modalShow();
                }, 
                (err) => {
                    showSystemMessage(mlBlade.forSelectPhotoTab.trans.fetchPhotoError, 'error');
                }
            );
        }
        else {
            this._selectModalTab('search_tab');
        }

        this._setMode('sp');
        this.modalShow();
    };

    /*
     * Sluzi za otvaranje "Photo Gallery" tab-a.
     */
    MediaLibrary.prototype.openPhotoGallery = function(onInsertCallback, galleryId) {
        if(typeof onInsertCallback === 'function') {
            window._mediaLibraryVm.state.photoGalleryTab.onInsertCallback = onInsertCallback;
        }
        else {
            console.error('MediaLibrary Error: openPhotoGallery() -> callback argument must be a valid function callback.');
            return false;
        }

        if(typeof galleryId !== 'undefined') {
            if(typeof galleryId === 'number') {
                window._mediaLibraryVm.loadGallery(galleryId,
                    () => {
                        window._mediaLibraryVm.state.photoGalleryTab.galleryId = galleryId;
                    },
                    (err) => {
                        showSystemMessage(mlBlade.forPhotoGalleryTab.trans.fetchGalleryError, 'error');
                    }
                );
                this._selectModalTab('photo_gallery_tab');
            }
            else {
                console.error('MediaLibrary Error: openPhotoGallery() -> galleryId argument must be a number.');
                return false;
            }
        }
        else {
            window._mediaLibraryVm.state.photoGalleryTab.galleryId = null;
            this._selectModalTab('search_tab');
        }

        this._setMode('pg');
        this.modalShow();
    };

    /**
     * Vrati podatke slike
     */
    MediaLibrary.prototype.getPhoto = function(photoId, callback, thumbSizeId) {
        if(typeof callback !== 'function') {
            console.error('MediaLibrary Error: getPhoto() -> callback argument must be a valid function callback.');
            return false;
        }

        let dataToSend = {
            'photo_id': photoId
        };

        if(typeof thumbSizeId !== 'undefined') {
            dataToSend.thumb_id = thumbSizeId;
        }
        else {
            thumbSizeId = mlBlade.forSearchTab.defaultThumbId;
        }

        // validiraj photoId i thumbSizeId
        let validated = this._validateFields(dataToSend, { 
            photo_id: {required: true, filled: true, mustAbide: (val) => {
                    return _.isNumber(val) ? true : 'Field must be a number'
                }
            },
            thumb_id: {required: false, filled: true, valueIn: _.map(mlBlade.mediaThumbs, 'id')}
        });

        if(validated !== true) {
            console.error("MediaLibrary Error: getPhoto() -> Received parameters invalid. Errors:");
            console.error(validated);
            return false;
        }

        // ukoliko je slika vec 'load'-ovana onda vrati vec postojece podatke
        if(photoId == window._mediaLibraryVm.state.active.imageObj.photoId) {
            console.log("getPhoto(): Serviram vec 'load'-ovanu sliku");

            let imgObj = _.clone(window._mediaLibraryVm.state.active.imageObj);
            if(imgObj.photoThumbSizeId !== thumbSizeId) {
                imgObj.photoImgSrc = imgObj.photoAllImgSources[thumbSizeId];
                imgObj.photoThumbSizeId = thumbSizeId;
            }

            return callback(imgObj);
        }

        $.ajax({
            url: mlBlade.forSelectPhotoTab.getImageDataAjaxUrl,
            type: 'POST',
            data: dataToSend
        }).done((res) => {
            if(res && res.status == 'ok' && res.data) {
                callback(res.data);
            }
        }).fail((err) => {
            console.error("Media Library: getPhoto() -> AJAX ERROR! "); 
            console.error(err);
        });
    }
</script>
@endpush