<input type="hidden" name="back_url" value="{{ $back_url }}">

<!-- Subject Form Text -->
<div class="form-group">
    <label class="checkbox-container">Active
        <input type="checkbox" name="active" value="1" {{ $activechecked }}>
        <span class="checkmark"></span>
    </label>
</div>

<div class="form-group">
    {!! Form::label('subject', 'Subject') !!}
    {!! Form::text('subject', NULL, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
    {!! Form::label('official_date', 'Official Date') !!}
    <div class='input-group date'>
        {!! Form::text('official_date', NULL, ['class' => 'form-control', 'id' => 'official_date', 'readonly' => true]) !!}
        <span class="input-group-btn">
            <button id="reset_official_date" class="btn btn-default" type="button" style="border-radius: 0;">reset</button>
        </span>
        <span class="input-group-addon">
			<span class="glyphicon glyphicon-calendar"></span>
		</span>
    </div>
</div>

<div class="form-group">
    {!! Form::label('published_at', 'Published At') !!}
    <div class='input-group date' id="published_at">
        {!! Form::text('published_at', NULL, ['class' => 'form-control', 'readonly' => true]) !!}
        <span class="input-group-btn">
            <button id="reset_published_at" class="btn btn-default" type="button" style="border-radius: 0;">reset</button>
        </span>
        <span class="input-group-addon">
			<span class="glyphicon glyphicon-calendar"></span>
		</span>
    </div>
</div>

<!-- Newsletter View -->
<div class="form-group" id="newsletter_template_container"></div>

<!-- Form Submit -->
<div class="form-group">
    {!! Form::submit($submit_title, ['class' => 'btn btn-primary form-control']) !!}
</div>

<div id="hidden_newsletter_elements"></div>

<!-- Banner Modal -->
<div class="modal fade" tabindex="-1" role="dialog" id="banner_modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Select a Banner</h4>
            </div>
            <div class="modal-body">
                <div class="form-group" id="banner_drop_down_container">
                </div>
                <div class="form-group text-center">
                    <img src="" id="banner_preview_source" class="img-responsive center-block">
                </div>
                <div class="form-group">
                    <iframe src="" width="568" height="450" frameborder="0" id="banner_preview_link" style="-webkit-transform:scale(1);-moz-transform-scale(1);"></iframe>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="delete_banner" class="pull-left btn btn-danger">Delete</button>
                <button type="button" data-dismiss="modal" class="btn btn-default">Close</button>
                <button type="button" id="save_banner" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

<!-- Article Modal -->
<div class="modal fade" role="dialog" id="article_modal">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Select an Article</h4>
            </div>
            <div class="modal-body article-select-modal">
                <!-- Article id Form Select -->
                <div class="form-group">
                    <!--  Form Select -->
                    <div class="form-group">
                        {!! Form::select('article_id', $articles, NULL, ['id' => 'article_id', 'class' => 'form-control', 'style' => 'width: 100%', 'placeholder' => 'Select an Option']) !!}
                    </div>
                </div>
                @include('admin.partials.image_cropping.element', [
                    'name' => 'article_image_source',
                    'save_path' => '/media/images/newsletter/cropped/',
                    'smaller' => 'false',
                    'height' => '130',
                	'width' => '130',
                    'file_manager_modal' => TRUE,
                ])
            </div>
            <div class="modal-footer">
                <button type="button" id="delete_article" class="pull-left btn btn-danger">Delete</button>
                <button type="button" data-dismiss="modal" class="btn btn-default">Close</button>
                <button type="button" id="save_article" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

@include('admin.partials.reload')

@push('scripts')
    <script>

        "use strict";

        //BANNER GLOBALS
        var banner_list; //table tbody tag that holds all the side banners
        var current_banner_container; //the currently clicked on banner that the modal is open to
        var banner_modal = $('#banner_modal'); //the modal that has the banner inputs

        //ARTICLE GLOBALS
        var article_list; //table tbody tag that holds all the secondary articles
        var current_article_container; //the currently clicked on article that the modal is open to
        var article_modal = $('#article_modal'); //the  modal that has the article inputs
        var current_article_id = '';

        //NEWSLETTER GLOBALS
        var newsletter_body_container; //the tbody tag that encompasses the newsletter article and banner rows

        //used to keep the user from being able to click on a different box before the current modal has a chance to save and set its data.
        var modal_check = true;

        $(function () {

            //load the newsletter template
            get_newsletter_template();

            /**
             *
             * ARTICLE SCRIPT SECTION
             *
             */

            //set article list to select2
            $('#article_id').chosen({
                                        width: "100%",
                                        display_disabled_options: false
                                    });

            //set official date to datetimepicker
            $('#official_date').datetimepicker({
                                                   minView       : 2,
                                                   startDate     : '{{ \Carbon\Carbon::now()->format('Y-m-d') }}',
                                                   format        : 'yyyy-mm-dd',
                                                   todayBtn      : true,
                                                   todayHighlight: true,
                                                   autoclose: true,
                                                   'timezone'    : 'EST'
                                               })
                               .on('changeDate', function (ev) {

                                   var official_date = $('#official_date').val();

                                   $.post('/newsletter/get_newsletter_template_corporate_block', {official_date: official_date}, function (data) {

                                       $('#corp_news_article_list').html(data);
                                   });
                               });

            $('#reset_official_date').click(function () {

                $('#official_date').val('');
            });

            $('#published_at').datetimepicker({
                  showMeridian  : true,
                  startDate     : '{{ \Carbon\Carbon::now()->addMinutes(30)->format('Y-m-d G:i') }}',
                  format        : 'yyyy-mm-dd hh:ii:ss',
                  todayBtn      : true,
                  todayHighlight: true,
                  autoclose: true,
                  pickerPosition: "bottom-left",
              });

            $('#reset_published_at').click(function () {

                $('#published_at input').val('');
            });

            /**
             * selects the article and shows the image that needs to be cropped
             */
            $('#article_id').change(function () {

                //grab the article id
                var article_id = this.value;

                //grab the article model
                $.post('/article/article_image', {article_id: article_id}, function (data) {

                    //extract the image source, width, height
                    var source = data.source;
                    var width  = current_article_container.data('image_width');
                    var height = current_article_container.data('image_height');

                    //set the cropping tool with new width and height and source
                    set_cropping_tool({
                                          image_cropping_container: $('.image_cropping_container', article_modal),
                                          buttonDone              : true,
                                          width                   : width,
                                          height                  : height,
                                          source                  : source
                                      });
                });
            });

            /**
             * sets the banner in the slot selected
             */
            $('#save_article').click(function () {

                //once the modal closes users won't be able to click on other boxes until this one saves and modal_check resets to true
                modal_check = false;

                $('#article_modal').modal('hide');

                //article information
                var article_id = $('#article_id', article_modal).val();

                //image information
                var source     = $('#article_image_source', article_modal).val();
                var image_type = current_article_container.data('image_type');

                //article location on the newsletter, "primary" = top spot OR "secondary" = article list section
                var type = current_article_container.data('type');

                //disable the option
                $('#article_id').find('option[value=' + article_id + ']').attr('disabled', true);
                $('#article_id').trigger('chosen:updated');

                $.post('/newsletter/get_newsletter_template_article_block', {
                    article_id: article_id,
                    source    : source,
                    image_type: image_type,
                    type      : type
                }, function (data) {

                    if (type === 'primary') {
                        current_article_container.replaceWith(data); //replaces the "click here..." with the new article block.
                    } else { // type = secondary
                        article_list.append(data); // adds a full secondary article block to the end
                    }

                    modal_check = true;

                    update_top_articles();
                }).fail(function () {

                    console.log('Get Article Block Failed!');
                    modal_check = true;
                });
            });

            /**
             * Removes the row from the article list section
             */
            $('#delete_article').click(function () {

                //once the modal closes users won't be able to click on other boxes until this one saves and modal_check resets to true
                modal_check = false;

                article_modal.modal('hide');

                //update the select dropdown undisable the article
                //disable the option
                $('#article_id').find('option[value=' + current_article_id + ']').attr('disabled', false);
                $('#article_id').trigger('chosen:updated');

                //only want to remove items that are in article list
                if (current_article_container.parent('#article_list').length > 0) {

                    current_article_container.remove();

                    modal_check = true;
                } else {

                    $.post('/newsletter/get_newsletter_template_article_block', {type: 'primary', view: 'dev'}, function (data) {

                        current_article_container.replaceWith(data);

                        modal_check = true;
                    });
                }

                update_top_articles();
            });

            /**
             *
             * BANNER SCRIPT SECTION
             *
             */

            /**
             * sets the iframe source and image source to preview the banner and banner link
             */
            banner_modal.on('change', '#banner_drop_down', function () {

                //get the selected option data attributes
                var current_banner_option = $('option:selected', this);
                var banner_preview_link   = current_banner_option.data('link');
                var banner_preview_source = current_banner_option.data('source');

                //set the data attributes to the iframe and image source
                $('#banner_preview_link').attr('src', banner_preview_link);
                $('#banner_preview_source').attr('src', banner_preview_source);
            });

            if ($("#banner_drop_down option:selected").val() != "") {
                console.log($("#banner_drop_down option:selected").val());
            }

            $('.add_banner').each(function(){
                var banner_id              = $(this).data('banner_id');
                var newsletter_banner_type = $(this).data('newsletter_banner_type');
                var banner_type            = $(this).data('banner_type');

                get_banner_block({
                                     banner_id             : banner_id,
                                     banner_type           : banner_type,
                                     newsletter_banner_type: newsletter_banner_type
                                 });
            })

            /**
             * sets the banner in the slot selected
             */
            $('#save_banner').click(function () {

                //once the modal closes users won't be able to click on other boxes until this one saves and modal_check resets to true
                modal_check = false;

                $('#banner_modal').modal('hide');

                var banner_id              = $('#banner_drop_down option:selected').val();
                var newsletter_banner_type = current_banner_container.data('newsletter_banner_type');
                var banner_type            = current_banner_container.data('banner_type');

                get_banner_block({
                                     banner_id             : banner_id,
                                     banner_type           : banner_type,
                                     newsletter_banner_type: newsletter_banner_type
                                 });
            });

            /**
             * Removes the row from the article list section
             */
            $('#delete_banner').click(function () {

                //once the modal closes users won't be able to click on other boxes until this one saves and modal_check resets to true
                modal_check = false;

                banner_modal.modal('hide');

                //only want to remove items that are in article list
                if (current_banner_container.parent('#banner_list').length > 0) {

                    current_banner_container.remove();

                    current_banner_container = '';

                    modal_check = true;
                } else {

                    get_banner_block({
                                         newsletter_banner_type: current_banner_container.data('newsletter_banner_type'),
                                         banner_type           : current_banner_container.data('banner_type')
                                     });
                }
            });
        });

        function get_newsletter_template() {

            $.post('/newsletter/get_newsletter_template_block', {dev: true, newsletter_id: '{{ isset($newsletter->id) ? $newsletter->id : '' }}'}, function (data) {

                $('#newsletter_template_container').html(data);

                update_top_articles();

                newsletter_body_container = $('#newsletter_body_container');

                load_on_newsletter_template();
            });
        }

        function load_on_newsletter_template() {

            //ARTICLE GLOBALS
            article_list               = $('#article_list', newsletter_body_container);
            var corp_news_article_list = $('#corp_news_article_list', newsletter_body_container);

            //BANNER GLOBALS
            banner_list = $('#banner_list');

            /**
             *
             * ARTICLE SCRIPT SECTION
             *
             */

            //Secondary Article Sorting
            article_list.sortable({
                                      placeholder: 'ui-state-highlight',
                                      update     : function () {

                                          console.log('Sortable Update Event Triggered');

                                          update_top_articles();
                                      }
                                  });

            article_list.disableSelection();

            //Corporate News Article Sorting
            corp_news_article_list.sortable({
                                                placeholder: 'ui-state-highlight'
                                            });

            corp_news_article_list.disableSelection();

            /**
             * show the article modal
             */
            newsletter_body_container.on('click', '.add_article', function () {

                current_article_id = $(this).data('article_id');

                if (modal_check) {

                    //set currently clicked article slot to global
                    current_article_container = $(this);

                    //reset article modal form elements
                    reset_article_modal();

                    //show the article modal
                    article_modal.modal('show');
                }

                return false;
            });

            /**
             *
             * BANNER SCRIPT SECTION
             *
             */

            //sets the banner list to a sortable list
            banner_list.sortable({
                                     placeholder: 'ui-state-highlight'
                                 });

            banner_list.disableSelection();

            /**
             * sets the ads into the the modal based on the clicked size and
             * shows the banner modal
             */
            $.fn.modal.Constructor.prototype.enforceFocus = function () {
            };

            newsletter_body_container.on('click', '.add_banner', function () {

                if (modal_check) {

                    //banner size
                    var banner_type = $(this).data('banner_type');
                    var banner_id = $(this).data('banner_id');

                    //reset the banner modal form elements
                    reset_banner_modal();

                    //set current banner
                    current_banner_container = $(this);

                    $.post('/banner/get_banner_list', {banner_type: banner_type, banner_id:banner_id}, function (data) {

                        //add select dropdown from banner_dropdown view
                        $('#banner_drop_down_container').html(data);

                        //set the dropdown to use select2
                        $('#banner_drop_down', $('#banner_drop_down_container')).select2({
                                                                                             width      : '100%',
                                                                                             placeholder: 'Select a Banner...'
                                                                                         });

                        //show the banner modal
                        $('#banner_modal').modal('show');
                    });
                }

                return false;
            });
        }

        function get_banner_block(data) {

            $.post('/newsletter/get_newsletter_template_banner_block', {banner_id: data.banner_id, newsletter_banner_type: data.newsletter_banner_type, banner_type: data.banner_type}, function (data) {
                if (current_banner_container[0].type === 'button') {

                    //banner blocks that are a list of banners
                    banner_list.append(data);
                } else {

                    //banner blocks that are single banners
                    current_banner_container.replaceWith(data);
                }

                modal_check = true;
            }).fail(function () {

                console.log('Get Banner Block Failed!');
                modal_check = true;
            });
        }

        function reset_banner_modal() {

            //image
            $('#banner_preview_source').attr('src', '');

            //iframe
            $('#banner_preview_link').attr('src', '');
        }

        function reset_article_modal() {

            //reset dropdown
            $('#article_id').val('').trigger('chosen:updated');

            set_image_cropping_cropped_source({
                                                  element_id: 'article_image_source',
                                                  source    : ''
                                              });

            set_cropping_tool({
                                  image_cropping_container: $('.image_cropping_container', article_modal),
                                  buttonDone              : true,
                                  width                   : current_article_container.data('image_width'),
                                  height                  : current_article_container.data('image_height')
                              });
        }

        function update_top_articles() {

            var articles = '';

            $('.article_title').each(function (key) {

                articles += '<a target="_blank" href="' + $(this).attr('href') + '" style="color: #333333; text-decoration: none;">' + $(this).html() + '</a>';

                if (key === 2) return false;

                articles += '<br>';
            });

            $('#top_articles').html(articles);
        }

        function selectArticle(el) {
            var checkBox = $(el);
            // Get the output text
            var input = checkBox.closest("li").find('input');
            var article_id = checkBox.closest("li").find('.article-id').html();
            checkBox.toggleClass('glyphicon-ok');
            // If the checkbox is checked, display the output text
            if (checkBox.hasClass('glyphicon-ok')){
                input.val(article_id);
            } else {
                input.val('');
            }
        }
    </script>
@endpush
