<?php $__env->startPush('head_scripts'); ?>
<style>
    .tab-content .article-content .cke_1 {
        max-width: 100%;
    }
</style>
<?php $__env->stopPush(); ?>
<form id="entity-form" method="post"
      action=""
      enctype="multipart/form-data" autocomplete="off">
    <?php echo csrf_field(); ?>
    <div class="article-errors">
        <?php echo $__env->make($namespace . 'partials.form.errors', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>
    <ul class="nav nav-tabs" role="tablist">
        <li class="nav-item">
            <a class="nav-link active" id="tekst-tab-1" data-toggle="tab" href="#tekst-1" role="tab"
               aria-controls="tekst-1"
               aria-selected="false">
                <span class="d-block d-sm-none"><i class="fa fa-home"></i></span>
                <span class="d-none d-sm-block"><?php echo app('translator')->get('Tekst'); ?></span>
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="slike-tab-1" data-toggle="tab" href="#slike-1" role="tab"
               aria-controls="slike-1" aria-selected="true">
                <span class="d-block d-sm-none"><i class="fa fa-user"></i></span>
                <span class="d-none d-sm-block"><?php echo app('translator')->get('Slike'); ?></span>
            </a>
        </li>
        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('articles-approve')): ?>
        <li class="nav-item" style="display: none;">
            <a class="nav-link" id="kategorije-tab-1" data-toggle="tab" href="#kategorije-1" role="tab"
               aria-controls="kategorije-1"
               aria-selected="false">
                <span class="d-block d-sm-none"><i class="fa fa-envelope-o"></i></span>
                <span class="d-none d-sm-block"><?php echo app('translator')->get('Kategorije'); ?></span>
            </a>
        </li>
        <?php endif; ?>
        <?php if(!$entity->exists): ?>
        <div class="ml-auto mt-1 order-0">
            <button class="btn btn-sm btn-secondary waves-effect waves-light ml-2 newest-article nav-buttons" type="button" title="<?php echo app('translator')->get('Najnovija vest'); ?>">
                <i class="fa fa-pencil-square-o" aria-hidden="true"></i>
                <span class="button-label"><?php echo app('translator')->get('Najnovija vest'); ?></span>
            </button>




        </div>
        <?php endif; ?>
    </ul>

    <div class="tab-content">
        <div class="tab-pane show active" id="tekst-1" role="tabpanel" aria-labelledby="tekst-tab-1">
            <div class="py-2 article-selectors">
                <?php echo $__env->make($namespace . 'partials.form.selectors', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            </div>
            <?php
            // <hr>
            // <div class="p-2 article-importer">
            //     @include($namespace . 'partials.form.importer')
            // </div>
            ?>
            <hr>
            <div class="p-2 article-sources">
                <?php echo $__env->make($namespace . 'partials.form.sources', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            </div>
            <hr>
            <?php if(request()->segment(count(request()->segments())) == 'edit'): ?>
                <button id="open_lead_embed_modal_edit" type="button" class="btn btn-sm btn-secondary waves-effect waves-light ml-2" name="open_video_modal">
                    <?php echo app('translator')->get('Dodaj/Izmeni vodeći video'); ?>
                </button>
                <div class="lead_video_wrapper">
                    <?php if(!empty($embedCode)): ?>
                        <?php echo $__env->make('articles.partials.form.embed_video', ['embedCode' => $embedCode], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <button id="open_lead_embed_modal_create" type="button" class="btn btn-sm btn-secondary waves-effect waves-light ml-2" name="open_video_modal">
                    <?php echo app('translator')->get('Dodaj vodeći video'); ?>
                </button>
                <div class="lead_video_wrapper">
                    <input id="leadVideoInput" type="hidden" name="embed_code_lead_video" value="">
                </div>
            <?php endif; ?>
            <hr>
            
            <div class="p-2 article-content">
                <?php echo $__env->make($namespace . 'partials.form.content', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
            </div>
            <?php
            // <hr>
            // <div class="p-2 article-related">
            //     @include($namespace . 'partials.form.related')
            // </div>
            ?>
        </div>
        <div class="tab-pane article-images" id="slike-1" role="tabpanel" aria-labelledby="slike-tab-1">
            <?php echo $__env->make($namespace . 'partials.form.images', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        </div>
        <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('articles-approve')): ?>
        <div 
            class="tab-pane article-categories" 
            id="kategorije-1" 
            role="tabpanel" 
            aria-labelledby="kategorije-tab-1" 
            style="display: none;"
        >
            <?php echo $__env->make($namespace . 'partials.form.categories', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
        </div>
        <?php endif; ?>
    </div>
    <hr>
    <?php if(request()->segment(count(request()->segments())) == 'edit'): ?>
    <?php echo $__env->make('articles.partials.form.related', ['relatedArticles' => $relatedArticles], \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
   
    <hr>
    <?php endif; ?>
    <div class="article-errors">
        <?php echo $__env->make($namespace . 'partials.form.errors', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    </div>
    <div class="form-group row justify-content-end">
        <div class="col-12 d-flex flex-wrap justify-content-end">
            <?php if($entity->exists): ?>
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('articles-delete')): ?>
            <button id="delete-article" class="btn btn-sm btn-danger waves-effect waves-light ml-2 empty-form" type="button">
                <?php echo app('translator')->get('Obriši'); ?>
            </button>
            <?php endif; ?>
            <?php endif; ?>
            <button id="cancel" class="btn btn-sm btn-secondary waves-effect waves-light ml-2 empty-form" type="reset">
                <?php echo app('translator')->get('Odustani'); ?>
            </button>
            <button type="submit" class="btn btn-sm btn-secondary waves-effect waves-light ml-2" value="save" name="save">
                <?php echo app('translator')->get('Sačuvaj'); ?>
            </button>
            <button type="submit" class="btn btn-sm btn-secondary waves-effect waves-light ml-2" value="save-and-edit"
                    name="save">
                <?php echo app('translator')->get('Sačuvaj i Ostani'); ?>
            </button>
            <?php if(request()->segment(count(request()->segments())) == 'edit'): ?>
            <button type="submit" class="btn btn-sm btn-success waves-effect waves-light ml-2" value="save-and-change"
                    name="save">
                <?php echo app('translator')->get('Izmeni'); ?>
            </button>
            <?php endif; ?>
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('articles-approve')): ?>
            <button type="submit" class="btn btn-sm btn-warning waves-effect waves-light ml-2" value="save-and-approve"
                    name="save">
                <i class="fa fa-check-circle"></i>
                <?php echo app('translator')->get('Sačuvaj i Odobri'); ?>
            </button>
            <?php endif; ?>
        </div>
    </div>
    <?php if(request()->segment(count(request()->segments())) == 'edit'): ?>
    <hr>
    <div class="form-group row">
        <?php if($entity->exists): ?>
        
        <div class="col-10 d-flex flex-wrap justify-content-start">
            <?php if (app(\Illuminate\Contracts\Auth\Access\Gate::class)->check('push')): ?>
            <div class="text-center">
            <button 
                type="button" 
                <?php if($entity->pushNot(config('website.main_site_id'), null)): ?>
                <?php if(optional($entity->pushNotification->where('site_id', config('website.main_site_id'))->first())->ended_at): ?>
                class="btn btn-success mr-1 mb-2"
                <?php else: ?>
                class="btn btn-primary mr-1 mb-2"
                <?php endif; ?>
                data-push-notification="<?php echo e($entity->pushNotification->where('site_id', config('website.main_site_id'))->pluck('id')->first()); ?>"
                <?php else: ?>
                class="btn btn-secondary mr-1 mb-2"
                <?php endif; ?>
                data-toggle="modal" 
                data-action="push"
                data-target="#push-form-modal"
                data-id="<?php echo e($entity->id); ?>"
                data-name="<?php echo e($entity->heading); ?>"
                data-type-name="WEB"
                data-main-url="<?php echo e($entity->getMainUrl()); ?>"
                data-site-id="<?php echo e(config('website.main_site_id')); ?>"
                style="width:120px;"
            >
            <?php echo app('translator')->get('push web'); ?>
            </button>
            <span data-type-web>
            <?php if($entity->pushNot(config('website.main_site_id'), null)): ?>
                <span class="d-block mb-2">
                    <span><?php echo e($entity->pushNotification->where('site_id', config('website.main_site_id'))->first()->userTo->first_name); ?>:</span>
                    <span class="d-block"><?php echo e($entity->pushNotification->where('site_id', config('website.main_site_id'))->first()->push_at->format('d.m.y H:i')); ?></span>
                </span>
            <?php endif; ?>
            <span>
            </div>
            <div class="text-center">
            <button 
                type="button" 
                <?php if($entity->pushNot(null, 'android')): ?>
                <?php if(optional($entity->pushNotification->where('type', 'android')->first())->ended_at): ?>
                class="btn btn-success mr-1 mb-2"
                <?php else: ?>
                class="btn btn-primary mr-1 mb-2"
                <?php endif; ?>
                data-push-notification="<?php echo e($entity->pushNotification->where('type', 'android')->pluck('id')->first()); ?>"
                <?php else: ?>
                class="btn btn-secondary mr-1 mb-2"
                <?php endif; ?>
                data-toggle="modal" 
                data-target="#push-form-modal"
                data-action="push"
                data-id="<?php echo e($entity->id); ?>"
                data-name="<?php echo e($entity->heading); ?>"
                data-type='android'
                data-type-name='ANDROID'
                data-main-url="<?php echo e($entity->getMainUrl()); ?>"
                style="width:120px;"
            >
            <?php echo app('translator')->get('push android'); ?>
            </button>
            <span data-type-android>
                <?php if($entity->pushNot(null, 'android')): ?>
                <span name="span" class="d-block mb-2">
                    <span><?php echo e($entity->pushNotification->where('type', 'android')->first()->userTo->first_name); ?>:</span>
                    <span class="d-block"><?php echo e(optional($entity->pushNotification->where('type', 'android')->first()->push_at)->format('d.m.y H:i')); ?></span>
                </span>
                <?php endif; ?>
            </span>
            </div>
            <div class="text-center">
            <button 
                type="button" 
                <?php if($entity->pushNot(null, 'ios')): ?>
                <?php if(optional($entity->pushNotification->where('type', 'ios')->first())->ended_at): ?>
                class="btn btn-success mr-1 mb-2"
                <?php else: ?>
                class="btn btn-primary mr-1 mb-2"
                <?php endif; ?>
                data-push-notification="<?php echo e($entity->pushNotification->where('type', 'ios')->pluck('id')->first()); ?>"
                <?php else: ?>
                class="btn btn-secondary mr-1 mb-2"
                <?php endif; ?>
                data-toggle="modal" 
                data-target="#push-form-modal"
                data-action="push"
                data-id="<?php echo e($entity->id); ?>"
                data-name="<?php echo e($entity->heading); ?>"
                data-type='ios'
                data-type-name='IOS'
                data-main-url="<?php echo e($entity->getMainUrl()); ?>"
                style="width:120px;"
            >
                <?php echo app('translator')->get('push ios'); ?>
            </button>
            <span data-type-ios>
            <?php if($entity->pushNot(null, 'ios')): ?>
                <span class="d-block mb-2">
                    <span><?php echo e($entity->pushNotification->where('type', 'ios')->first()->userTo->first_name); ?>:</span>
                    <span class="d-block"><?php echo e($entity->pushNotification->where('type', 'ios')->first()->push_at->format('d.m.y H:i')); ?></span>
                </span>
            <?php endif; ?>
            <span>
            </div>
            <?php endif; ?>
        </div>
        
        <?php endif; ?>
    </div>
    
    <?php endif; ?>
</form>
<form action="<?php echo e(route('push.push')); ?>" method="post" class="modal" id="push-form-modal">
    <?php echo csrf_field(); ?>
    <input type="hidden" name="article_id" value="">
    <input type="hidden" name="site_id" value="">
    <input type="hidden" name="type" value="">
    <input type="hidden" name="push_id" value="">
    
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 style="color: black" class="modal-title"><b><?php echo app('translator')->get('Push Notifications'); ?></b></h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p><?php echo app('translator')->get('Da li si ste sigurni da zelite da posaljete'); ?> <strong data-container="type"></strong> <?php echo app('translator')->get('notifikaciju za trenutnu vest'); ?>?</p>
                <p><?php echo app('translator')->get('Naslov'); ?>: <strong data-container="name"></strong></p>
                <hr>
                <p><?php echo app('translator')->get('Link'); ?>: <a data-container="main-url" target="blank"></a></p>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-default" data-dismiss="modal"><?php echo app('translator')->get('Cancel'); ?></button>
                <button type="submit" class="btn btn-success">
                    <?php echo app('translator')->get('Push'); ?>
                </button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</form>
<?php $__env->startPush('head_links'); ?>
    <style>
        .cursor-pointer {
            cursor: pointer;
        }
    </style>
<?php $__env->stopPush(); ?>
<div class="article-modals">
    <?php echo $__env->make($namespace . 'partials.modals.polls', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.social_embed', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.video', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.embed_lead_video_create', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.embed_lead_video_edit', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.related_news', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make($namespace . 'partials.modals.lead_video', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
    <?php echo $__env->make('_layout.partials.modal.media_library.modal', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
</div>
<?php $__env->startPush('footer_scripts'); ?>
<script src="<?php echo e(asset('/custom/js/modal-management.js')); ?>"></script>
    <script>
        $(document).ready(function () {
            //*************************************HANDLE SELECTS FUNCTION********************************************//

            var updateSelect = function (element, jsonData, category = false, destroyElement = false) {
                let siteId = element.data('website-id');
                let data = jsonData.filter(function (n) {
                    if (category) {
                        return n.site_id == siteId && n.parent_id == category;
                    } else {
                        return n.site_id == siteId;
                    }
                }).map(function (obj) {
                    return {
                        'id': obj.id,
                        'text': obj.text
                    }
                });

                if (destroyElement) {
                    destroyElement.select2('destroy').empty();
                    destroyElement.select2({
                        minimumResultsForSearch: -1,
                        data: data
                    });
                } else {
                    element.select2({
                        minimumResultsForSearch: -1,
                        data: data
                    });
                }
            };
            //*************************************MAIN CATEGORIES****************************************************//

            var mainCategories = JSON.parse('<?php echo $mainCategories; ?>');
            var mainSubcategories = JSON.parse('<?php echo $mainSubCategories; ?>');

            $('.article-selectors select').each(function (key, item) {
                if ($(this).hasClass('select-category')) {
                    updateSelect($(this), mainCategories);

                } else if ($(this).hasClass('select-subcategory')) {
                    let siteId = $(this).data('website-id');
                    let selectedCategory = $('.article-selectors select.select-category[data-website-id=' + siteId + ']').val();
                    updateSelect($(this), mainSubcategories, selectedCategory);

                }
            });

            $('.article-selectors select.select-category').on('change', function (e) {
                let siteId = $(this).data('website-id');
                let category = $(this).val();
                updateSelect($(this), mainSubcategories, category, $('.article-selectors select.select-subcategory[data-website-id=' + siteId + ']'));
            });


            //*************************************CATEGORIES********************************************************//
            var categories = JSON.parse('<?php echo $categories; ?>');
            var subCategories = JSON.parse('<?php echo $subCategories; ?>');

            $('.article-categories select').each(function (key, item) {
                if ($(this).hasClass('select-category')) {
                    updateSelect($(this), categories);

                } else if ($(this).hasClass('select-subcategory')) {
                    let siteId = $(this).data('website-id');
                    let selectedCategory = $('.article-categories select.select-category[data-website-id=' + siteId + ']').val();
                    updateSelect($(this), subCategories, selectedCategory);

                }
            });

            $('.article-categories select.select-category').on('change', function (e) {
                let siteId = $(this).data('website-id');
                let category = $(this).val();
                updateSelect($(this), subCategories, category, $('.article-categories select.select-subcategory[data-website-id=' + siteId + ']'));
            });

            //*************************************VALIDATION********************************************************//

                $('#entity-form').validate({
                    rules: {
                        time_created: "required",
                        publish_at: {
                            required: function () {
                                return $('.article-selectors input.approve-approval-time').is(':checked');
                            }
                        },
                        category_id: "required",
                        subcategory_id: "required",
                        // TAGOVI
                        author_id: {
                            required: function () {
                                return $(".article-sources .select-source").val() == "";
                            }
                        },
                        source: {
                            required: function () {
                                return $(".article-sources .select-author").val() == "";
                            }
                        },
                        heading: {
                            required: true,
                            maxlength: 140
                        },
                        preheading: {
                            required: false,
                            maxlength: 25
                        },
                        text: "required",
                        image_f: "required",
                        image_iff: "required"

                    },
                    messages: {
                        time_created: "Polje Datum unosa je obavezno",
                        publish_at: "Polje za izbor datuma je obavezno ukoliko je odabrano polje 'Odobri u'",
                        category_id: "Polje Kategorija je obavezno",
                        subcategory_id: "Polje Podkategorija je obavezno",
                        author_id: "Morate navesti autora ili izvor",
                        source: "Morate navesti autora ili izvor",
                        heading: {
                            required: "Polje Naslov je obavezno",
                            maxlength: "Polje Naslov može da sadrži 140 karaktera maksimalno"
                        },
                        preheading: {
                            maxlength: "Polje Preheading može da sadrži 25 karaktera maksimalno"
                        },
                        text: "Polje Sadrzaj Vesti je obavezno",
                        image_f: "Obavezne su sve slike",
                        image_iff: "Obavezne su sve slike"
                    },
                    ignore: [],
                    errorElement: 'div',
                    errorLabelContainer: '.article-errors',
                    errorClass: 'text-danger alert alert-danger',
                    validClass: 'success',
                    highlight: function (element, errorClass, validClass) {
                        $(element).parents("div.form-group").addClass(errorClass).removeClass(validClass);
                    },
                    unhighlight: function (element, errorClass, validClass) {
                        $(element).parents("div .form-group").removeClass(errorClass).addClass(validClass);
                        $(element).parents("div.form-group").find('.custom-errors-abc').remove();
                    },
                    invalidHandler: function(e,validator) {
                        //validator.errorList contains an array of objects, where each object has properties "element" and "message".  element is the actual HTML Input.
                        for (var i=0;i<validator.errorList.length;i++){
                            console.log(validator.errorList[i]);
                            if(validator.errorList[i].element.localName == "select"){
                                if(!($(validator.errorList[i].element).parents("div.form-group").find('.custom-errors-abc').length)){
                                    $(validator.errorList[i].element).parents("div.form-group").find('div').append('<span class="custom-errors-abc d-block">'+validator.errorList[i].message+'</span>');
                                }
                            
                            }else{
                                if(!($(validator.errorList[i].element).parents("div.form-group").find('.custom-errors-abc').length)){
                                    $(validator.errorList[i].element).parents("div.form-group").append('<span class="custom-errors-abc d-block">'+validator.errorList[i].message+'</span>');
                                }
                            }
                            
                        }
                    }
                });

                $('.article-categories input.website-checker').each(function(key, item){
                    let webChecker = $(this);
                    let webCat = webChecker.parent().next().find('.select-category');
                    let webSubCat = webChecker.parent().next().find('.select-subcategory');
                    webCat.rules('add', {
                        required: function(){
                            return webChecker.is(':checked');
                        },
                        messages: {
                            required: "Polje kategorija za izabrani sajt " + webCat.data('website-name') + " je obavezno"
                        }
                    });
                    webSubCat.rules('add', {
                        required: function(){
                            return webChecker.is(':checked');
                        },
                        messages: {
                            required: "Polje podkategorija za izabrani sajt " + webSubCat.data('website-name') + " je obavezno"
                        }
                    });
                });

            //*************************************END VALIDATION*****************************************************//
            
                $('button#delete-article').on('click', function(e) {
                $('#entity-form').attr('action', "<?php echo e(route('articles.delete', ['entity' => $entity])); ?>");

                $('#entity-form').submit();
                });
                
                $('button#cancel').on('click', function(e) {
                    window.location.href = '/ajax-clear-autosave';
                });
                
                //OPEN MODAL RELATED NEWS
                $('.list-articles-for-related').on('click', function(e){
                    e.preventDefault();
                    let modal = $('#relatedArticlesModal');
                    modal.modal('show');
                    
                    $('.article-modals #relatedArticlesModal').attr('data-action', 'formModal');
                    console.log($('.article-modals #relatedArticlesModal'));
                });

                //REMOVE RELATED ARTICLE FROM THE LIST
                $('#entity-form').on('click', '[data-action="delete-related-article"]', function(e){
                    e.preventDefault();
                    var articleIdToRemove = $(this).attr('data-id');
                    var articleToRemove = $(this).closest('div.articleItem');

                    console.log(articleIdToRemove, articleToRemove);

                    let relatedArticles = $('#entity-form input[name="articleRelated[]"]');

                    relatedArticles.each(function(index){
                        if($(this).val() == articleIdToRemove){
                            articleToRemove.remove();
                            $(this).remove();
                            return false;
                        }
                    });
                });

                //QUICK RELATED ENTRY
                $('#entity-form .quick-related-entry').on('keypress', function(e){
                    let code = e.keyCode || e.which;
                    let articleId = $(this).val();
                    
                    if(code == 13){
                        $.ajax({
                            url: "<?= route('articles.get_related_article'); ?>",
                            type: "get",
                            data: {
                                articleId: articleId,
                                
                            }
                        }).done(function(response) {

                            let html = `<div class="articleItem">
                                <div style="background-color: rgba(0,0,0,0.03); border-bottom: 1px solid rgba(0,0,0,0.125)">
                                    <div class="pull-right mt-2" >
                                        <button class="btn btn-danger btn-xs align-self-center" data-action="delete-related-article" data-id="${response.id}">
                                            <i class="fa fa-trash"></i>
                                            <span class="ml-1"><?php echo app('translator')->get('Obriši'); ?></span>
                                        </button>
                                    </div>
                                </div>
                                <div class="row align-items-start m-l-10">
                                    <div class="col-2 list-article-thumb p-1">
                                        <img src="${response.image_t}" alt="${response.heading}" class="w-100 h-25">
                                    </div>
                                    <div class="col-10 list-article-properties align-self-center p-1">
                                        <p class="list-article-title mb-1">${response.heading}</p>
                                    </div>
                                
                                </div>
                            </div>
                            `;

                            $('#entity-form div.related-articles-wrapper').append(html);
                            $('#entity-form').append(`<input type="hidden" name="articleRelated[]" value="${response.id}">`);

                            showSystemMessage('Vest je dodata medju povezane vesti!');
                        
                        }).fail(function(err){
                            showSystemMessage('Vest nije dodata medju povezane vesti!', 'error');
                        });
                    }
                });

                $(document).on("keypress", 'form', function (e) {
                    let $articleForm = $('#entity-form');
                    if(e.which != 13) {
                        return;
                    }
                    e.preventDefault();
                });
                // sakrij deo sa povezanim vestima na dnu forme
                // na promenu taba
                $('#slike-tab-1').on('click', function(){
                    $('#entity-form div.related-under').hide();
                });
                // prikazi deo sa povezanim vestima na tekst tab-u
                $('#tekst-tab-1').on('click', function(){
                    $('#entity-form div.related-under').show();
                });

                function onOpenVideoModal(){
                    let modal = $('#leadVideoModal');
                    modal.modal('show');

                    let term = $('#leadVideoModal input[name="search_video"]').val();
                    let videosNumber = $('#leadVideoModal [name="articles_number"]').val();
                    let page = $('#leadVideoModal [name="page"]').val();

                    $.ajax({
                        url: "<?= route('articles.get_searched_videos'); ?>",
                        type: "get",
                        data: {
                            term: term,
                            videosNumber: videosNumber,
                            page: page
                        }
                    }).done(function(response) {
                        $('#leadVideoModal div.video-articles-loader').hide();
                        $('#leadVideoModal #videos').html(response);
                        
                    }).fail(function(jqXHR, textStatus, errorThrown){
                        $('#leadVideoModal #videos').html('<p><?php echo app('translator')->get('Nije pronadjen nijedan video'); ?></p>');
                    });
                }

                //OPEN VIDEO MODAL
                //OPEN LEAD VIDEO MODAL WITH EMBED CODE CREATE 
                $('#open_lead_embed_modal_create').on('click', function(e){
                    e.preventDefault();
                    let modal = $('#embedVideoModalCreate');
                    modal.modal('show');
                });

                //OPEN LEAD VIDEO MODAL WITH EMBED CODE EDIT 
                $('#open_lead_embed_modal_edit').on('click', function(e){
                    e.preventDefault();
                    let modal = $('#embedVideoModalEdit');
                    modal.modal('show');
                });

                //CHECK IF VIDEO HAS ALREADY BEEN ADDED
                //RETURN TRUE IF EXISTS
                function checkIfLeadVideoExistsCreate(){
                    let video =  $('#leadVideoInput').val();
                    console.log("create",video);
                    if(!video){
                        return false;
                    }
                    return true;
                }

                function checkIfLeadVideoExistsEdit(){
                    let video =  $('#leadVideoInputEdit').val();
                    console.log("edit",video);
                    if(!video){
                        return false;
                    }
                    return true;
                }

                    $('#embedVideoModalCreate').on('click', 'button.save', function(e){
                    e.preventDefault();
                    if(checkIfLeadVideoExistsCreate()){
                            showSystemMessage('Već postoji dodat video, uklonite stari da biste dodali novi!', 'error');
                        } else {
                            let modal = $('#embedVideoModalCreate');
                            let embed = $('#embedVideoModalCreate textarea[name="embed_code_lead_video"]').val();
                            console.log(embed);
                            html = `<div class="row justify-content-betweenn m-t-10">
                                        <div class="col-12">
                                            <div class="articleItem">
                                                
                                                <div style="background-color: rgba(0,0,0,0.03); border-bottom: 1px solid rgba(0,0,0,0.125)">
                                                    <div class="pull-right mt-4 mr-2" >
                                                        <button class="btn btn-danger btn-xs align-self-center" type="button" data-action="delete-video">
                                                            <i class="fa fa-trash"></i>
                                                            <span class="ml-1"><?php echo app('translator')->get('Obriši'); ?></span>
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                                <div class="row align-items-start m-l-10">
                                                    <div class="col-10 list-article-properties align-self-center p-1">
                                                        <p class="mb-1">
                                                            <strong><ins><?php echo app('translator')->get('Vodeći video'); ?></ins>:</strong> 
                                                        </p>
                                                        <div class="">
                                                            `+embed+`
                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    </div>`;
                                    $('#entity-form div.lead_video_wrapper').append(html);
                                    $('#entity-form input[name="embed_code_lead_video"]').val(embed);
                                    modal.modal('hide');
                                }
                    });
        
                $('#embedVideoModalEdit').on('click', 'button.edit', function(e){
                    e.preventDefault();
                    if(checkIfLeadVideoExistsEdit()){
                            showSystemMessage('Već postoji dodat video, uklonite stari da biste dodali novi!', 'error');
                        } else {
                            let modal = $('#embedVideoModalEdit');
                            let embed = $('#embedVideoModalEdit textarea[name="embed_code_lead_video"]').val();
                            console.log(embed);
                            html = `<div class="row justify-content-betweenn m-t-10">
                                        <div class="col-12">
                                            <div class="articleItem">
                                                <input id="leadVideoInputEdit" type="hidden" name="embed_code_lead_video" value="">
                                                <div style="background-color: rgba(0,0,0,0.03); border-bottom: 1px solid rgba(0,0,0,0.125)">
                                                    <div class="pull-right mt-4 mr-2" >
                                                        <button class="btn btn-danger btn-xs align-self-center" type="button" data-action="delete-video">
                                                            <i class="fa fa-trash"></i>
                                                            <span class="ml-1"><?php echo app('translator')->get('Obriši'); ?></span>
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                                <div class="row align-items-start m-l-10">
                                                    <div class="col-10 list-article-properties align-self-center p-1">
                                                        <p class="mb-1">
                                                            <strong><ins><?php echo app('translator')->get('Vodeci video'); ?></ins>:</strong> 
                                                        </p>
                                                        <div class="embed-responsive embed-responsive-16by9">
                                                            `+embed+`
                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    </div>`;
                            $('#entity-form div.lead_video_wrapper').append(html);
                            $('#entity-form input[name="embed_code_lead_video"]').val(embed);
                            modal.modal('hide');
                        }
                });

                
                //OPEN VIDEO MODAL

                //REMOVE VIDEO FROM FORM
                $('#entity-form').on('click', '[data-action="delete-video"]', function(e){
                    e.preventDefault();
                    $('#leadVideoInput').val("");
                    $('.lead_video_wrapper').html('');
                });

                $('#entity-form').on('click', '[data-action="delete"]', function(e){
                    e.preventDefault();
                    $('#leadVideoInputEdit').val("");
                    $('.lead_video_wrapper').html('');
                    let html = `<input id="leadVideoInputEdit" type="hidden" name="embed_code_lead_video" value=""/>`;
                    $("#entity-form div.lead_video_wrapper").append(html);
                });

                //PUSH MODAL NA FORMI
                $('#entity-form [data-action="push"]').on('click', function (e) {
                    //e.stopPropagation();
                    //e.preventDefault();

                    let id = $(this).attr('data-id');
                    let name = $(this).attr('data-name');
                    let siteId = $(this).attr('data-site-id');
                    let type = $(this).attr('data-type');
                    let typeName = $(this).attr('data-type-name');
                    let mainUrl = $(this).attr('data-main-url');
                    let pushId = $(this).attr('data-push-notification');

                    $('#push-form-modal [name="article_id"]').val(id);
                    $('#push-form-modal [name="site_id"]').val(siteId);
                    $('#push-form-modal [name="type"]').val(type);
                    $('#push-form-modal [name="push_id"]').val(pushId);
                    $('#push-form-modal [data-container="name"]').html(name);
                    $('#push-form-modal [data-container="type"]').html(typeName);
                    $('#push-form-modal [data-container="main-url"]').html(mainUrl);
                    $('#push-form-modal [data-container="main-url"]').attr("href", mainUrl)
                    
                });

                //funkcija za popunjavanja svih slika
                function insertAllImagesThumbs(thumbSizes) {
                    $.each(thumbSizes, function (key, item) {
                        $(`img[data-photo-thumb-type="${key}"]`).attr('src', item);
                        $(`input[name="image_${key}"]`).val(item);
                    });
                }

                //ajax poziv za zakazivanje push notifikacija sa forme artikla
                $('#push-form-modal').on('submit', function(e){
                    e.preventDefault();
                    e.stopPropagation();
                    let articleId = $('#push-form-modal [name="article_id"]').val();
                    let siteId = $('#push-form-modal [name="site_id"]').val();
                    let type = $('#push-form-modal [name="type"]').val();
                    let pushId = $('#push-form-modal [name="push_id"]').val();

                    $.ajax({
                        url: "<?php echo e(route('push.ajax.push')); ?>",
                        method: 'POST',
                        data: {
                            'article_id': articleId,
                            'site_id': siteId,
                            'type': type,
                            'push_id': pushId
                        }
                    }).done(function(response){
                        let html = `<span class="d-block mb-2">
                                <span>${response.data.username}:</span>
                                <span class="d-block">${response.data.pushtime}</span>
                                </span>`;
                        let pushId = response.data.pushId;
                        $('#push-form-modal').modal('hide');
                        if(response.data.dataType === 'ios'){
                            $('#entity-form [data-type="ios"]').addClass('btn btn-primary');
                            $('#entity-form [data-type="ios"]').removeClass('btn-success btn-secondary');
                            $('#entity-form [data-type-ios]').html(html);
                            $('#entity-form [data-type="ios"]').attr('data-push-notification', pushId);
                            
                        }
                        else if(response.data.dataType === 'android'){
                            $('#entity-form [data-type-android]').html(html)
                            $('#entity-form [data-type="android"]').addClass('btn btn-primary');
                            $('#entity-form [data-type="android"]').removeClass('btn-success btn-secondary');
                            $('#entity-form [data-type="android"]').attr('data-push-notification', pushId);
                        }else{
                            $('#entity-form [data-type-web]').html(html)
                            $('#entity-form [data-type-name="WEB"]').addClass('btn btn-primary');
                            $('#entity-form [data-type-name="WEB"]').removeClass('btn-success btn-secondary');
                            $('#entity-form [data-type-name="WEB"]').attr('data-push-notification', pushId);
                        }
                    });
                });

                //NAJNOVIJA VEST DUGME
                $('#entity-form .newest-article').on('click', function(e){
                    e.preventDefault();
                    e.stopPropagation();

                    $.ajax({
                        "url": "<?php echo e(route('get_newest_article_data')); ?>",
                        "type": "get",
                        "data": {}
                    }).done(function (response) {

                        let value = response.newest_article_tags;
                        if(value !== null){
                            insertAllImagesThumbs(response.images);
                        }

                        $('[name="tags[]"]').tagsSelect({
                            sourceUrl: '<?php echo e(route('tags.select_tag')); ?>',
                            storeUrl: '<?php echo e(route('tags.create_tag')); ?>',
                            showSystemMessageOnCreate: 'false',
                            enableCreate: 'true',
                            newTagLabel: " (<?php echo app('translator')->get('Dodaj novi tag'); ?>)",
                            datatables: 'entities-table',
                            value: value
                        });

                        $('input[name="time_created"]').val(response.time);
                        $('input#article-more-soon').prop( "checked", true );
                        // let li = `<li class="select2-selection__choice" title="Partizan KK"><span class="select2-selection__choice__remove" role="presentation">×</span>Partizan KK</li>`;
                        // $('ul.select2-selection__rendered').prepend(li);
                    });
                });

                $(document).on( "click", '.fillLead', function(e) {
                    e.preventDefault();
                    var desc = CKEDITOR.instances.contentEditor.getData();

                    function* findAllMatches(str,substr,caseInsensitive) 
                    {
                        const s = caseInsensitive ? str.toLowerCase() : str;
                        const m = caseInsensitive ? substr.toLowerCase() : substr;
                        let idx = -1;

                        while ((idx = s.indexOf(m, idx + 1)) !== -1) {
                            yield idx;
                        }
                    }

                    const positionStart = Array.from(findAllMatches(desc, "<p>", true));
                    const positionEnd = Array.from(findAllMatches(desc, "</p>", true));   
                    let slicedText = '';

                    $.each(positionStart, function( index, value ) {
                        var test = desc.slice(value + 3, positionEnd[index]) + '...';
                        var validator = test.slice(0, 2);
                        if(validator != '&n' && validator != '<i' && validator != '<a' && validator != '<b'){
                            if(test.length > 137){
                                slicedText = test.replace(/&nbsp;/g, '').replace(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/<strong>/g, '').replace(/<\/strong>/g, '').slice(0, 137) + '...';
                                return false; 
                            }
                            else{
                                slicedText = test.replace(/&nbsp;/g, '').replace(/&#39;/g, "'").replace(/&quot;/g, '"').replace(/<strong>/g, '').replace(/<\/strong>/g, '')+'...';
                                return false; 
                            }
                        }
                    });
                    
                    $('#leadTextArea').val(slicedText);
                });

        });
    </script>
<?php $__env->stopPush(); ?>
<?php /**PATH /opt/cms/resources/views/articles/partials/form.blade.php ENDPATH**/ ?>