<?php echo $header; ?>
<link href="<?php echo ADMIN_THEME; ?>/js/trevor/sir-trevor.css" rel="stylesheet">
<link href="<?php echo ADMIN_THEME; ?>/js/trevor/sir-trevor-bootstrap.css" rel="stylesheet">
<link href="<?php echo ADMIN_THEME; ?>/js/trevor/sir-trevor-icons.css" rel="stylesheet">
<link href="<?php echo ADMIN_THEME; ?>/js/datepicker/jquery.datetimepicker.css" rel="stylesheet">
<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <h1 class="page-header">
                <?php echo $this->lang->line('posts_edit_header'); ?>
            </h1>
            <ol class="breadcrumb">
                <li>
                    <i class="fa fa-dashboard"></i>
                    <a href="<?php echo BASE_URL; ?>/admin"><?php echo $this->lang->line('nav_dash'); ?></a>
                </li>
                <li>
                    <i class="fa fa-fw fa-newspaper-o"></i>
                    <a href="<?php echo BASE_URL; ?>/admin/posts"><?php echo $this->lang->line('nav_posts_all'); ?></a>
                </li>
                <li class="active">
                    <i class="fa fa-fw fa-pencil"></i>
                    <?php echo $this->lang->line('posts_edit_header'); ?>
                </li>
            </ol>
        </div>
    </div>
</div>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <?php echo form_error('postTitle', '<div class="alert alert-danger">', '</div>'); ?>
            <?php echo form_error('postURL', '<div class="alert alert-danger">', '</div>'); ?>
            <?php echo form_error('postExcerpt', '<div class="alert alert-danger">', '</div>'); ?>
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">
                        <i class="fa fa-pencil fa-fw"></i>
                        <?php echo $this->lang->line('posts_edit_header'); ?>
                    </h3>
                </div>

                <div class="panel-body">

                    <?php foreach ($posts as $p) {
                        echo form_error('postTitle', '<div class="alert alert-danger">', '</div>'); ?>
                    <?php echo form_error('postURL', '<div class="alert alert-danger">', '</div>'); ?>
                    <?php
                        $attr = array('id' => 'contentForm', 'class' => 'form-horizontal');
                        echo form_open(BASE_URL . '/admin/posts/edited/' . $this->uri->segment(4), $attr); ?>
                    <?php $data = array(
                            'id'          => 'content',
                            'name'          => 'content',
                            'class'       => 'js-st-instance',
                        );
                        if ($this->input->post('content')) {
                            $set = $this->input->post('content');
                        } else {
                            $set = $p['postContentHTML'];
                        }
                        echo form_textarea($data, set_value('content', $set, FALSE)); ?>
                </div>
                <div class="panel-footer">
                    <a class="btn btn-primary" data-toggle="modal"
                        href="#attributes"><?php echo $this->lang->line('btn_next'); ?></a>
                    <a class="btn"
                        href="<?php echo BASE_URL; ?>/admin/posts"><?php echo $this->lang->line('btn_cancel'); ?></a>
                    <a class="btn btn-info" target="_blank" href="<?php echo $posts[0]['articleURL'] ?>">미리보기</a>
                </div>
            </div>

            <div id="attributes" class="modal fade" role="dialog">
                <div class="modal-dialog">

                    <!-- Modal content-->
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                            <h4 class="modal-title"><?php echo $this->lang->line('posts_new_attributes'); ?></h4>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <div class="alert alert-info"><?php echo $this->lang->line('posts_new_required'); ?>
                                </div>
                                <?php echo form_error('postTitle', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="postTitle"><?php echo $this->lang->line('posts_new_title'); ?></label>
                                <div class="controls">
                                    <?php $data = array(
                                            'name'        => 'postTitle',
                                            'id'          => 'postTitle',
                                            'class'       => 'form-control',
                                            'value'        => set_value('postTitle', $p['postTitle'], FALSE)
                                        );

                                        echo form_input($data); ?>
                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                            <div class="form-group">                                
                                <?php echo form_error('postSubTitle', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="postTitle"><?php echo $this->lang->line('posts_new_subtitle'); ?></label>
                                <div class="controls">
                                    <?php $data = array(
                                            'name'        => 'postSubTitle',
                                            'id'          => 'postSubTitle',
                                            'class'       => 'form-control',
                                            'value'        => set_value('postSubTitle', $p['postSubTitle'], FALSE)
                                        );

                                        echo form_input($data); ?>
                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->


                            <div class="form-group">
                                <?php echo form_error('file_upload', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="file_upload"><?php echo $this->lang->line('posts_new_feature'); ?></label>
                                <div class="controls">
                                    <div><img
                                            src="<?php echo !empty($p['postImage']) ? getImageUrl($p['postImage']) : '' ?>"
                                            id="logo_preloaded" class="logo_preloaded"
                                            <?php echo empty($p['postImage']) ? "style='display:none;'" : '' ?>>
                                    </div>
                                    <img src="<?php echo BASE_URL; ?>/theme/admin/images/ajax-loader.gif"
                                        style="margin:-7px 5px 0 5px;display:none;" id="loading_pic"
                                        class="loading_pic" />
                                    <?php
                                        $data = array(
                                            'name'        => 'file_upload',
                                            'id'        => 'file_upload',
                                            'class'        => 'form-control file-upload'
                                        );
                                        echo form_upload($data);
                                        ?>
                                    <input type="hidden" id="postImage" class="postImage" name="postImage" />
                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                            <div class="form-group">
                                <?php echo form_error('file_upload_thumb', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="file_upload_thumb"><?php echo $this->lang->line('posts_new_thumb'); ?></label>
                                <div class="controls">
                                    <div>
                                        <img src="<?php echo getThumbUrl($p['postImage'], $p['postThumb']) ?>"
                                            id="logo_preloaded" class="logo_preloaded">
                                    </div>
                                    <img src="<?php echo BASE_URL; ?>/theme/admin/images/ajax-loader.gif"
                                        style="margin:-7px 5px 0 5px;display:none;" id="loading_pic"
                                        class="loading_pic" />
                                    <?php
                                        $data = array(
                                            'name'        => 'file_upload_thumb',
                                            'id'        => 'file_upload_thumb',
                                            'class'        => 'form-control file-upload'
                                        );
                                        echo form_upload($data);
                                        ?>
                                    <input type="hidden" id="postThumb" class="postImage" name="postThumb" />
                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                            <div class="form-group">
                                <label class="control-label"
                                    for="postExcerpt"><?php echo $this->lang->line('posts_new_excerpt'); ?></label>
                                <div class="controls">
                                    <?php $data = array(
                                            'name'        => 'postExcerpt',
                                            'id'          => 'postExcerpt',
                                            'class'       => 'form-control',
                                            'rows'        =>    '4',
                                        );

                                        echo form_textarea($data, set_value('postExcerpt', $p['postExcerpt'], FALSE)); ?>

                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                            <div class="form-group hide">
                                <?php echo form_error('postURL', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="postURL"><?php echo $this->lang->line('posts_new_url'); ?></label>
                                <div class="controls">
                                    <?php $data = array(
                                            'name'        => 'postURL',
                                            'id'          => 'postURL',
                                            'class'       => 'form-control URLField',
                                            'value'        => set_value('postURL', $p['postURL'], FALSE)
                                        );

                                        echo form_input($data); ?>

                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                            <div class="form-group">
                                <?php echo form_error('categoryID', '<div class="alert alert-danger">', '</div>'); ?>
                                <div class="form-group">
                                    <label class="control-label"
                                        for="categoryID"><?php echo $this->lang->line('posts_new_category'); ?></label>
                                    <a class="btn btn-warning btn-sm add-category-select"><i class="fa fa-plus"></i> Add
                                        category</a>
                                </div>
                                <div class="category-control hide">
                                    <div class="col-sm-2"><a class="btn btn-danger btn-sm delete-category-select"><i
                                                class="fa fa-times"></i> Delete</a></div>
                                    <div class="controls col-sm-10">
                                        <?php
                                            $data = array();
                                            foreach ($categories as $c) {
                                                $data[$c['categoryID']] = $c['categoryTitle'];
                                            }
                                            echo form_dropdown('categoryID', $data, 0); ?>
                                    </div>
                                </div>
                            </div> <!-- /form-group -->
                            <div class="form-group">
                                <?php echo form_error('pageID', '<div class="alert alert-danger">', '</div>'); ?>
                                <div class="form-group">
                                    <label class="control-label"
                                        for="pageID"><?php echo $this->lang->line('posts_new_page'); ?></label>
                                    <a class="btn btn-warning btn-sm add-page-select"><i class="fa fa-plus"></i> Add
                                        page</a>
                                </div>
                                <div class="page-control hide">
                                    <div class="col-sm-2"><a class="btn btn-danger btn-sm delete-page-select"><i
                                                class="fa fa-times"></i> Delete</a></div>
                                    <div class="controls col-sm-10">
                                        <?php
                                            $data = array();
                                            foreach ($pages as $c) {
                                                $data[$c['pageID']] = $c['pageTitle'];
                                            }
                                            echo form_dropdown('pageID', $data, 0); ?>
                                    </div>
                                </div>
                            </div> <!-- /form-group -->


                            <div class="form-group">
                                <?php echo form_error('pageID', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="userID"><?php echo $this->lang->line('posts_new_user'); ?></label>
                                <div class="controls">
                                    <?php
                                        $data = array();
                                        foreach ($users as $u) {
                                            $data[$u->userID] = $u->userName;
                                        }
                                        echo form_dropdown('userID', $data, (empty($posts[0]['userID']) ? $this->session->userdata('userID') : $posts[0]['userID']), ['class' => 'cm-writer']); ?>
                                </div>

                            </div> <!-- /form-group -->



                            <div class="form-group">
                                <?php echo form_error('published', '<div class="alert alert-danger">', '</div>'); ?>
                                <label class="control-label"
                                    for="published"><?php echo $this->lang->line('posts_new_published'); ?></label>
                                <div class="controls">
                                    <?php
                                        $att = 'id="published" class="form-control"';
                                        $data = array(
                                            1 => 'Yes',
                                            0 => 'No'
                                        );

                                        echo form_dropdown('published', $data, $p['published'], $att); ?>
                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->
                            <div class="form-group">
                                <div id="datetimepicker1" class="input-append date">
                                    <label class="control-label"
                                        for="dateReserved"><?php echo $this->lang->line('posts_reserved_date'); ?></label>
                                    <div class="controls">
                                        <?php $data = array(
                                                'name'        => 'dateReserved',
                                                'id'          => 'datetimepicker',
                                                'class'       => 'form-control',
                                                'value'        => set_value('dateReserved', (empty($p['dateReserved']) ? 0:$p['dateReserved']) , FALSE)
                                            );

                                            echo form_input($data); ?>


                                        <?php $data = array(
                                                'name'        => 'unixStamp',
                                                'id'          => 'unixStamp',
                                                'style'        => 'display:none;',
                                                'value'        => set_value('unixStamp', $p['unixStamp'], FALSE)
                                            );

                                            echo form_input($data); ?>

                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label class="control-label"
                                    for="postTag"><?php echo $this->lang->line('posts_new_tag'); ?></label>
                                <div class="controls">
                                    <?php $data = array(
                                            'name'        => 'postTag',
                                            'id'          => 'postTag',
                                            'class'       => 'form-control',
                                            'rows'        =>    '4',
                                        );

                                        echo form_textarea($data, set_value('postTag', '', FALSE)); ?>

                                </div> <!-- /controls -->
                            </div> <!-- /form-group -->

                        </div>
                        <div class="modal-footer">
                            <button class="btn" data-dismiss="modal"
                                aria-hidden="true"><?php echo $this->lang->line('btn_back'); ?></button>
                            <a class="btn btn-primary"
                                onClick="formSubmit()"><?php echo $this->lang->line('btn_save'); ?></a>
                        </div>
                    </div>
                    <input type="hidden" name="categories">
                    <input type="hidden" name="pages">
                    <input type="hidden" name="video" value="<?php echo $video ?>">
                    <?php echo form_close();
                    } ?>
                </div>
                <!-- /colmd12 -->

            </div>
            <!-- /row -->
        </div>

        <script src="<?php echo ADMIN_THEME; ?>/js/datepicker/jquery.datetimepicker.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/trevor/underscore.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/trevor/eventable.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/trevor/sortable.min.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/trevor/sir-trevor.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/trevor/sir-trevor-bootstrap.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/date.js"></script>
        <script src="<?php echo ADMIN_THEME; ?>/js/tinymce/tinymce.min.js"></script>

        <script type="text/javascript">
        jQuery('#datetimepicker').datetimepicker({
            format: 'm/d/Y H:m:s'
        });
        // new SirTrevor.Editor({ el: $('.js-st-instance'),
        // 	blockTypes: ["Columns", "Heading", "Text", "ImageExtended", "Quote", "Accordion", "Button", "Video", "List", "Iframe"]
        // });
        // SirTrevor.onBeforeSubmit();
        </script>
        <script>
        $(function() {
            tinyMCE.init({
                selector: '.js-st-instance',
                plugins: ['link image code fullscreen lineheight',
                    'autolink lists link anchor table', 
                    'textcolor colorpicker textpattern'
                ],
                file_browser_callback: RoxyFileBrowser,
                language: 'ko_KR',
                image_advtab: true,
                toolbar: 'codesample | bold italic sizeselect fontselect fontsizeselect | hr alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | insertfile undo redo | forecolor backcolor emoticons | code | lineheightselect | table tabledelete | tableprops tablerowprops tablecellprops | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol',
                fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
                font_formats: '나눔고딕=나눔고딕코딩,NanumGothicCoding,sans-serif; Andale Mono=andale mono,times; Arial=arial,helvetica,sans-serif; Arial Black=arial black,avant garde; Book Antiqua=book antiqua,palatino; Comic Sans MS=comic sans ms,sans-serif; Courier New=courier new,courier; Georgia=georgia,palatino; Helvetica=helvetica; Impact=impact,chicago; Symbol=symbol; Tahoma=tahoma,arial,helvetica,sans-serif; Terminal=terminal,monaco; Times New Roman=times new roman,times; Trebuchet MS=trebuchet ms,geneva; Verdana=verdana,geneva; Webdings=webdings; Wingdings=wingdings,zapf dingbats',
                lineheight_formats: "1pt 2pt 3pt 4pt 5pt 6pt 7pt 8pt 9pt 10pt 11pt 12pt 14pt 16pt 18pt 20pt 22pt 24pt 26pt 36pt 48pt",
                setup: function(ed) {
                    ed.on('init', function() {
                        // this.getDoc().body.style.fontSize = '12';
                        this.getDoc().body.style.fontFamily = '나눔고딕';
                    });
                }
            });
        });

        function RoxyFileBrowser(field_name, url, type, win) {
            var roxyFileman = '/fileman/index.html?integration=tinymce4';
            if (roxyFileman.indexOf("?") < 0) {
                roxyFileman += "?type=" + type;
            } else {
                roxyFileman += "&type=" + type;
            }
            roxyFileman += '&input=' + field_name + '&value=' + win.document.getElementById(field_name).value;
            if (tinyMCE.activeEditor.settings.language) {
                roxyFileman += '&langCode=' + tinyMCE.activeEditor.settings.language;
            }
            tinyMCE.activeEditor.windowManager.open({
                file: roxyFileman,
                title: 'Crossmap File Manager',
                width: 850,
                height: 650,
                resizable: "yes",
                plugins: "media",
                inline: "yes",
                close_previous: "no"
            }, {
                window: win,
                input: field_name
            });
            return false;
        }
        </script>
        <script type="text/javascript">
        function formSubmit() {
            $.ajax({
                url: "/admin/check/session",
            }).done(function(data) {
                sessionExist = data;
                if (sessionExist == 0) {
                    $('.modal').modal('hide');
                    $('#loginModal').modal({
                        backdrop: 'static',
                        keyboard: false
                    }).modal('show');
                } else {
                    SirTrevor.onBeforeSubmit();
                    var unixtime = Date.parse(document.getElementById('datetimepicker').value).getTime() / 1000;
                    document.getElementById("unixStamp").value = unixtime;
                    document.getElementById("contentForm").categories.value = $.map($(
                        '.category-control select'), function(el, i) {
                        if (i && el.value != '0') return el.value
                    }).join(',');
                    document.getElementById("contentForm").pages.value = $.map($(
                        '.page-control select'), function(el, i) {
                        if (i && el.value != '0') return el.value
                    }).join(',');
                    document.getElementById("contentForm").submit();
                }
            });
        }
        </script>
        <script type="text/javascript">
        $(function() {
            var postPages = <?php echo json_encode($posts[0]['pages']) ?>;
            var postCategories = <?php echo json_encode($posts[0]['categories']) ?>;
            var addedElement = {
                category: null,
                page: null
            };
            $('.add-category-select').on('click', function(e) {
                addedElement.category = $(".category-control")
                    .parent().append(
                        $(".category-control")
                        .first()
                        .clone()
                    ).children('.category-control').last().removeClass('hide').find("select").select2({
                        width: '100%'
                    });
                $(".category-control")
                    .parent().children('.category-control').last().find('.delete-category-select').on(
                        'click',
                        function(e) {
                            $(this).parent().parent().remove();
                        });
            });

            $('.add-page-select').on('click', function(e) {
                addedElement.page = $(".page-control")
                    .parent().append(
                        $(".page-control")
                        .first()
                        .clone()
                    ).children('.page-control').last().removeClass('hide').find("select").select2({
                        width: '100%'
                    });
                $(".page-control")
                    .parent().children('.page-control').last().find('.delete-page-select').on(
                        'click',
                        function(e) {
                            $(this).parent().parent().remove();
                        });
            });

            $('.modal').on('shown.bs.modal', function(e) {
                if (postCategories.length) {
                    $.map(postCategories, function(v, k) {
                        $('.add-category-select').trigger('click');
                        $('.category-control').last().find('select').val(v);
                        $('.category-control').last().find('select').trigger('change');
                    })
                } else {
                    $('.add-category-select').trigger('click');
                    $('.page-control').last().find('select').val(0);
                    $('.page-control').last().find('select').trigger('change');
                }
                $('.cm-writer').select2({
                    width: '100%'
                });
            });


            $('.modal').on('shown.bs.modal', function(e) {
                if (postPages.length) {
                    $.map(postPages, function(v, k) {
                        $('.add-page-select').trigger('click');
                        $('.page-control').last().find('select').val(v);
                        $('.page-control').last().find('select').trigger('change');
                    })
                } else {
                    $('.add-page-select').trigger('click');
                }
            })


            // function submitForm(event, data) {
            //     $form = $(event.target);
            //     var formData = $form.serialize();
            //     $.each(data.files, function(key, value) {
            //         formData = formData + '&filenames[]=' + value;
            //     });

            //     $.ajax({
            //         url: '<?php echo BASE_URL; ?>/admin/settings/submit',
            //         type: 'POST',
            //         data: formData,
            //         cache: false,
            //         dataType: 'json',
            //         success: function(data, textStatus, jqXHR) {
            //             if (typeof data.error === 'undefined')
            //                 console.log('SUCCESS: ' + data.success);
            //             else
            //                 console.log('ERRORS: ' + data.error);
            //         },
            //         error: function(jqXHR, textStatus, errorThrown) {
            //             console.log('ERRORS: ' + textStatus);
            //         },
            //         complete: function() {
            //             $('#loading_pic').hide();
            //         }
            //     });
            // }

            $.map($('input[type=file]'), function(elem, k) {
                $(elem).on('change', function(e) {
                    var elem = this;
                    (function(e) {
                        e.stopPropagation();
                        e.preventDefault();
                        if ($(elem).val()) {
                            $('.loading_pic').eq(k).show();
                            var data = new FormData();
                            $.each(e.target.files, function(key, value) {
                                data.append(key, value);
                            });
                            $.ajax({
                                url: '<?php echo BASE_URL; ?>/admin/settings/submit/?files',
                                type: 'POST',
                                data: data,
                                cache: false,
                                dataType: 'json',
                                processData: false,
                                contentType: false,
                                success: function(data, textStatus, jqXHR) {
                                    if (data != '0') {
                                        $('.logo_preloaded').eq(k).show();
                                        $('.logo_preloaded').eq(k).attr('src',
                                            '/uploads/' + data);
                                        $('.postImage').eq(k).val(data);
                                        $('.loading_pic').eq(k).hide();
                                    } else
                                        alert(
                                            'Error! The file is not an image.');
                                }
                            });
                        }
                    })(e);
                })
            });

            $('textarea[name=postTag]').tagEditor({
                initialTags: <?php echo $posts[0]['postTag']?>
            });
        });
        </script>
        <?php echo $footer; ?>