$(function () {
    CM = { fn: {}, el: {} }
    $('.select2').select2();

    if ($(".cm-table").length) {
        $.extend(CM.fn, {
            titleFormatter: function (value, row, index) {
                return '<a href="javascript:;" class="cm-title-link" data-index="' + index + '">' + value + '</a>' + (row.isSetDptime ? ' <i class="glyphicon glyphicon-time"></i>' + row.display_date : '')
            },
            imageFormatter: function (value, row, index) {
                return '<img src="' + (value.indexOf('://') > -1 ? '' : 'https://crossmap.christiandaily.co.kr') + value + '" class="cm-list-img-size"/>'
            },
            operateFormatter: function (value, row, index) {
                var operateBtns = [
                    '<a class="edit" href="javascript:void(0)" title="Edit">',
                    '<i class="glyphicon glyphicon-edit"></i>',
                    '</a> ',
                    '<a class="remove" href="javascript:void(0)" title="Remove">',
                    '<i class="glyphicon glyphicon-remove"></i>',
                    '</a>'
                ];
                return operateBtns.join('');
            },
            operateEvents: {
                'click .edit': function (e, value, row, index) {
                    CM.el.editDpModal.find('.cm-config-add .cm-saved-config-dp-edit-btn').data('post-id', row.idx);
                    CM.el.editDpModal.find('.cm-config-add .cm-set-content-title-head').val(row.title);
                    CM.el.editDpModal.find('.cm-config-add .cm-set-content-title').val(row.title);
                    CM.el.editDpModal.find('.cm-set-dptime-content-title').val(row.title);
                    CM.el.editDpModal.find('.cm-set-content-display .cm-uploaded-img').attr('src', (row.mainImg.indexOf('://') > -1 ? '' : 'https://crossmap.christiandaily.co.kr') + row.mainImg).show();
                    CM.el.editDpModal.modal('show')
                },
                'click .remove': function (e, value, row, index) {
                    bootbox.confirm('삭제할까요?', function (ok) {
                        if (ok) {
                            $.ajax({
                                url: '/adm/' + location.href.split('/')[4] + '/content_delete',
                                method: 'DELETE',
                                data: JSON.stringify({ contentId: row.idx }),
                                dataType: 'json'
                            }).done(function (res) {
                                if (res.code != 200) {
                                    bootbox.alert(res.message)
                                } else {
                                    bootbox.alert('삭제되었습니다.')
                                    CM.el.searchBtn.trigger('click')
                                }
                            });
                        }
                    });
                }
            },
            operateCommentEvents: {
                'click .edit': function (e, value, row, index) {

                },
                'click .remove': function (e, value, row, index) {
                    bootbox.confirm('삭제할까요?', function (ok) {
                        if (ok) {
                            $.ajax({
                                url: '/adm/' + location.href.split('/')[4] + '/content_delete',
                                method: 'DELETE',
                                data: JSON.stringify({ contentId: row.commentId }),
                                dataType: 'json'
                            }).done(function (res) {
                                if (res.code != 200) {
                                    bootbox.alert(res.message)
                                } else {
                                    bootbox.alert('삭제되었습니다.')
                                    CM.el.searchBtn.trigger('click')
                                }
                            });
                        }
                    });
                }
            }
        });
        $.extend(CM.el, {
            categorySelect: $('.cm-submenu-select'),
            subChgBtn: $('.cm-submenuchg-btn').on('click', function (e) {
                if (CM.el.table.bootstrapTable('getSelections').length) CM.el.submenuChangeModal.modal('show'); else bootbox.alert('선택')
            }),
            subChgCatSelect: $('.cm-subchg-category-select'),
            subChgEditorSelect: $('.cm-subchg-editor-select'),
            categoryChangeBtn: $('.cm-submenuchange-save').on('click', function (e) {
                bootbox.confirm('이동할까요?', function (ok) {
                    if (ok) {
                        $.ajax({
                            url: '/adm/' + location.href.split('/')[4] + '/content_category',
                            method: 'PUT',
                            data: JSON.stringify({
                                contentId: $.map(CM.el.table.bootstrapTable('getSelections'), function (r) {
                                    return r.idx
                                }), category: CM.el.subChgCatSelect.val(), editor: CM.el.subChgEditorSelect.val()
                            }),
                            dataType: 'json'
                        }).done(function (res) {
                            if (res.code != 200) {
                                bootbox.alert(res.message)
                            } else {
                                bootbox.alert(CM.el.table.bootstrapTable('getSelections').length + ' 개의 글이 이동하였습니다')
                                CM.el.submenuChangeModal.modal('hide')
                                CM.el.searchBtn.trigger('click')
                            }
                        });
                    }
                })
            }),
            hiddenForm: $('.cm-hidden-form'),
            editorSelect: $('.cm-editor-select'),
            searchWord: $('.cm-search-word').on('keypress', function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    CM.el.searchBtn.trigger('click')
                }
            }),
            searchBtn: $('.cm-search-btn').on('click', function () {
                CM.el.table.bootstrapTable('refresh')
            }),
            submenuChangeModal: $('.cm-submenuchange-modal').on('hide.bs.modal', function () {
                $(this).find('form')[0].reset();
            }),
            editDpModal: $('.cm-editdp-modal').on('hide.bs.modal', function () {
                $.map($(this).find('form'), function (el) { el.reset() })
                CM.el.tabConfigContentDptime.trigger('click')
            })
        });
        $(".cm-table").bootstrapTable({
            queryParams: function (params) {
                return $.extend(params, {
                    term: CM.el.searchWord.val(),
                    editor: CM.el.editorSelect.val(),
                    category: CM.el.categorySelect.val()
                })
            }
        }).on('load-success.bs.table', function () {
            CM.el.table = $(this)
            $('.cm-title-link').on('click', function (e) {
                var row = CM.el.table.bootstrapTable('getData')[$(e.target).data('index')]
                var frm = CM.el.hiddenForm[0];
                frm.idx.value = row.idx;
                frm.mode.value = 'edit';
                frm.action = '/admin/life/life_reg/5';
                frm.submit();
            })
        });
    }
    if ($(".cm-category-table").length) {
        $.extend(CM.fn, {
            operateFormatter: function (value, row, index) {
                var operateBtns = [
                    '<a class="edit" href="javascript:void(0)" title="Edit">',
                    '<i class="glyphicon glyphicon-edit"></i>',
                    '</a> ',
                    '<a class="remove" href="javascript:void(0)" title="Remove">',
                    '<i class="glyphicon glyphicon-remove"></i>',
                    '</a>'
                ];
                return operateBtns.join('');
            },
            operateEvents: {
                'click .edit': function (e, value, row, index) {
                    CM.el.editModal.find('form')[0].id.value = row.categoryId;
                    CM.el.editModal.find('.cm-submenu-categoryname').val(row.categoryName);
                    CM.el.editModal.find('.cm-submenu-dporder').val(row.displayOrder);
                    CM.el.editModal.modal('show');
                },
                'click .remove': function (e, value, row, index) {
                    bootbox.confirm('삭제할까요?', function (ok) {
                        if (ok) {
                            $.ajax({
                                url: '/adm/' + location.href.split('/')[4] + '/category_delete',
                                method: 'DELETE',
                                data: JSON.stringify({ id: row.categoryId }),
                                dataType: 'json'
                            }).done(function (res) {
                                if (res.code != 200) {
                                    bootbox.alert(res.message)
                                } else {
                                    bootbox.alert('삭제되었습니다.')
                                    CM.el.searchBtn.trigger('click')
                                }
                            });
                        }
                    });
                }
            }
        });
        $.extend(CM.el, {

            searchWord: $('.cm-search-word').on('keypress', function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    CM.el.searchBtn.trigger('click')
                }
            }),
            searchBtn: $('.cm-search-btn').on('click', function () {
                CM.el.table.bootstrapTable('refresh')
            }),
            editModal: $('.cm-submenu-modal').on('hide.bs.modal', function () {
                $(this).find('form')[0].id.value = ''; $(this).find('form')[0].reset();
            }),
            editSaveBtn: $('.cm-submenu-save').on('click', function () {
                var params = {
                    id: CM.el.editModal.find('form')[0].id.value,
                    name: CM.el.editModal.find('.cm-submenu-categoryname').val(),
                    order: CM.el.editModal.find('.cm-submenu-dporder').val()
                }
                $.ajax({
                    url: '/adm/' + location.href.split('/')[4] + '/category_save',
                    method: 'PUT',
                    data: JSON.stringify(params),
                    dataType: 'json',
                    contentType: 'application/json'
                }).done(function (res) {
                    if (res.code != 200) {
                        bootbox.alert(res.message)
                    } else {
                        bootbox.alert((params.id ? '변경' : '추가') + ' 되었습니다.')
                        CM.el.searchBtn.trigger('click')
                        CM.el.editModal.modal('hide')
                    }
                });
            })
        });
        $(".cm-category-table").bootstrapTable({
            queryParams: function (params) {
                return $.extend(params, {
                    term: CM.el.searchWord.val()
                })
            }
        }).on('load-success.bs.table', function () {
            CM.el.table = $(this)
        });
    }
    if ($('.cm-upload-file').length) {
        $('.cm-upload-file').on('change', function () {
            var frm = $(this).parents('form')
            frm.ajaxSubmit(function (res) {
                if (res.code != 200) {
                    bootbox.alert(res.message)
                } else {
                    frm.find('.cm-uploaded-img').attr('src', res.data.url).show()
                }
            })
        })
    }
    if ($('.cm-set-content-display').length) {
        CM.fn.contentDisplayData = function () {
            return CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').data('update') == 'Y' ? {
                type: 'display',
                id: CM.el.tabpanelConfigContentDisplay.find('.cm-config-edit .cm-saved-config-dp-edit-btn').data('config-id'),
                postid: CM.el.tabpanelConfigContentDisplay.find('.cm-config-edit .cm-saved-config-dp-edit-btn').data('post-id'),
                name: CM.el.tabConfigContentDisplay.data('name'),
                page: CM.el.tabpanelConfigContentDisplay.find('form')[0].dp_part.value,
                title: CM.el.tabpanelConfigContentDisplay.find('.cm-config-edit .cm-set-content-title').val(),
                headline: CM.el.tabpanelConfigContentDisplay.find('.cm-config-edit .cm-set-content-title-head').val(),
                order: CM.el.tabpanelConfigContentDisplay.find('.cm-config-edit .cm-set-content-order').val(),
                thumbnail: CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').attr('src'),
            } : {
                    type: 'display',
                    postid: CM.el.tabpanelConfigContentDisplay.find('.cm-config-add .cm-saved-config-dp-edit-btn').data('post-id'),
                    name: CM.el.tabConfigContentDisplay.data('name'),
                    page: CM.el.tabpanelConfigContentDisplay.find('form')[0].dp_part.value,
                    title: CM.el.tabpanelConfigContentDisplay.find('.cm-config-add .cm-set-content-title').val(),
                    headline: CM.el.tabpanelConfigContentDisplay.find('.cm-config-add .cm-set-content-title-head').val(),
                    order: CM.el.tabpanelConfigContentDisplay.find('.cm-config-add .cm-set-content-order').val(),
                    thumbnail: CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').attr('src'),
                };
        }
        CM.el.saveConfigEditBtn = $('.cm-saved-config-dp-edit-btn').on('change', function () {
            if (this.value == 'edit') {
                var changed = this;
                $(this).parents('.cm-config-display').addClass('cm-config-edit');
                $(this).prev().show();
                CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').data('update', 'Y').attr('src', $(this).data('config-thumbnail')).show();
                CM.el.tabpanelConfigContentDisplay.find('.cm-config-add').hide();
                $.map($('.cm-saved-config-dp-edit-btn'), function (el) { if (el != changed) { el.selectedIndex = 0, $(el).prev().hide() } })
            } else if (this.value == 'delete') {
                $.ajax({
                    url: '/adm/content/config',
                    method: 'DELETE',
                    data: JSON.stringify({ id: $(this).data('config-id') }),
                    dataType: 'json'
                }).done(function (res) {
                    if (res.code != 200) {
                        alert(res.message)
                    } else {
                        alert(res.message)
                        CM.el.tabpanelConfigContentDisplay.find('form')[0].reset();
                        CM.el.tabpanelConfigContentDisplay.find('.cm-config-add').show();
                        CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').data('update', 'N')
                        $('.cm-set-content-dp-part:checked').trigger('click')
                    }
                });
            }
        })
        CM.el.editDpModal.on('show.bs.modal', function () {
            $('.cm-config-display-copy').remove();
        });
        CM.el.tabConfigContentDptime = $('a[href=".cm-set-content-dptime"]');
        CM.el.tabConfigDptimeDatepicker = $('.cm-set-dptime').datetimepicker({ format: 'YYYY-MM-DD HH:mm:ss' });
        CM.el.tabConfigContentDisplay = $('a[href=".cm-set-content-display"]').on('show.bs.tab', function () {
            $.ajax({
                url: '/adm/content/config',
                method: 'PUT',
                data: JSON.stringify({
                    type: 'display',
                    name: $(this).data('name'),
                    page: CM.el.tabpanelConfigContentDisplay.find('form')[0].dp_part.value
                }),
                dataType: 'json'
            }).done(function (res) {
                $('.cm-config-display-copy').remove();
                if (res.code != 200) {
                    bootbox.alert(res.message)
                } else if (res.data.length) {
                    var dp = $('.cm-config-add');
                    for (var i = 0; i < res.data.length; i++) {
                        var dpc = dp.clone(true);
                        dpc.removeClass('cm-config-add')
                        dpc.addClass('cm-config-display-copy')
                        dpc.find('.cm-set-content-order').val(res.data[i].OrderNum);
                        dpc.find('.cm-set-content-title-head').val(res.data[i].Headline);
                        dpc.find('.cm-set-content-title').val(res.data[i].Title);
                        dpc.find('.cm-saved-config-dp-edit-btn').data('post-id', res.data[i].PostId).data('config-id', res.data[i].Id).data('config-thumbnail', res.data[i].Thumbnail).show();
                        dp.before(dpc);
                    }
                }
            });
        });
        $('.cm-set-content-dp-part').on('click', function () {
            CM.el.tabConfigContentDisplay.trigger('show.bs.tab')
            CM.el.tabpanelConfigContentDisplay.find('.cm-config-add').show();
        });
        CM.el.tabpanelConfigDptime = $('.cm-set-content-dptime');
        CM.el.tabpanelConfigDptime.find('.btn-primary').on('click', function () {
            if (CM.el.tabConfigDptimeDatepicker.val()) {
                $.ajax({
                    url: '/adm/content/config',
                    method: 'POST',
                    data: JSON.stringify({
                        dptime: CM.el.tabConfigDptimeDatepicker.val(),
                        postid: CM.el.tabpanelConfigContentDisplay.find('.cm-config-add .cm-saved-config-dp-edit-btn').data('post-id'),
                        type: 'dptime'
                    }),
                    dataType: 'json'
                }).done(function (res) {
                    if (res.code != 200) {
                        alert(res.message)
                    } else {
                        alert(res.message)
                        CM.el.searchBtn.trigger('click');
                        CM.el.editDpModal.modal('hide')
                    }
                });
            } else {
                alert('예약시간 설정')
            }
        });
        CM.el.tabpanelConfigContentDisplay = $('.cm-set-content-display')
        CM.el.tabpanelConfigContentDisplay.find('.btn-primary').on('click', function () {
            if (CM.fn.contentDisplayData().order && CM.fn.contentDisplayData().title) {
                $.ajax({
                    url: '/adm/content/config',
                    method: 'POST',
                    data: JSON.stringify(CM.fn.contentDisplayData()),
                    dataType: 'json'
                }).done(function (res) {
                    if (res.code != 200) {
                        alert(res.message)
                    } else {
                        alert(res.message)
                        var checked = $('.cm-set-content-dp-part:checked').trigger('click')
                        CM.el.tabpanelConfigContentDisplay.find('form')[0].reset();
                        checked[0].checked = true;
                        CM.el.tabpanelConfigContentDisplay.find('.cm-uploaded-img').data('update', 'N').hide();
                    }
                });
            } else {
                alert('정보입력')
            }
        })
    }


    if ($("#flot-chart-pie").length) {
        var data = [
            { label: "Series 0", data: 1 },
            { label: "Series 1", data: 3 },
            { label: "Series 2", data: 9 },
            { label: "Series 3", data: 20 }
        ];

        var plotObj = $.plot($("#flot-chart-pie"), data, {
            series: {
                pie: {
                    show: true
                }
            },
            grid: {
                hoverable: true
            },
            tooltip: true,
            tooltipOpts: {
                content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
                shifts: {
                    x: 20,
                    y: 0
                },
                defaultTheme: false
            }
        });

    }

    if ($("#flot-chart-line").length) {
        var offset = 0;
        plot();
        function plot() {
            var sin = [], cos = [];
            for (var i = 0; i < 12; i += 0.2) {
                sin.push([i, Math.sin(i + offset)]);
                cos.push([i, Math.cos(i + offset)]);
            }

            var options = {
                series: {
                    lines: { show: true },
                    points: { show: true }
                },
                grid: {
                    hoverable: true //IMPORTANT! this is needed for tooltip to work
                },
                yaxis: { min: -1.2, max: 1.2 },
                tooltip: true,
                tooltipOpts: {
                    content: "'%s' of %x.1 is %y.4",
                    shifts: {
                        x: -60,
                        y: 25
                    }
                }
            };

            var plotObj = $.plot($("#flot-chart-line"),
                [{ data: sin, label: "sin(x)" }, { data: cos, label: "cos(x)" }],
                options);
        }
    }

    if($('.cm-register-btn').length) {
        $('.cm-register-btn').on('click', function(){
            $('.cm-register-modal').modal('show')
        })
    }
})