var AdminLTEOptions = { animationSpeed: 'fast' };

try { SHOW } catch (e) { SHOW = { fn: {}, var: { youtubeSearchRetry: 0 }, nod: {}, formatter: {}, event: {} } }


SHOW.formatter.searchYoutubeVideoPreview = function (value, row, index) {
    return '<img src="' + row.thumbnails.default.url + '" class="video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/' + row.id + '" data-target="#previewModal">';
}

SHOW.formatter.videoListPreview = function (value, row, index) {

    return '<img src="https://i.ytimg.com/vi/' + row.code + '/default.jpg" class="video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/' + row.code + '" data-target="#previewModal">';
}

SHOW.formatter.categoryImageFormatter = function (value, row, index) {
    return row.image ? '<img src="/upload/category/' + row.image + '" height="50">' : '';
}

SHOW.formatter.categoryNameFormatter = function (value, row, index) {
    return '<a href="/data/index?app=' + row.app + '&category=' + row.id + '">' + value + '</a>';
}

SHOW.fn.categorySubCountFormatter = function (value, row, index) {
    return '<button class="btn btn-sm btn-default category-subsidiary" data-parent="' + row.id + '">' + value + '</button>';
}


SHOW.formatter.searchYoutubeVideoDuration = function (value, row, index) {
    var duration = [];
    if (row.duration) {
        if (row.duration.hours) {
            duration.push(SHOW.fn.pad(row.duration.hours, 2))
        }
        if (row.duration.minutes) {
            duration.push(SHOW.fn.pad(row.duration.minutes, 2))
        }
        if (row.duration.seconds) {
            duration.push(SHOW.fn.pad(row.duration.seconds, 2))
        }
        return duration.join(':');
    }
    return '';
}

SHOW.node = function (identifier) {
    return SHOW.nod[identifier] || (SHOW.nod[identifier] = $(identifier))
}

SHOW.fn.refreshTable = function () {
    SHOW.node('#show-table').bootstrapTable('refresh')
}

SHOW.fn.pad = function (n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

SHOW.fn.findVideo = function (selection, callback) {
    $.post('/data/find_video', selection, function (res) {
        if (res.code == 200 && res.data.duplicateCount == 0) {
            callback(selection);
        } else if (res.data.duplicateCount > 0) {
            alert('서버에 이미 저장된 비디오 ' + res.data.duplicateCount + '건을 선택하셨습니다.')
            if (confirm('중복건 제외하고 저장할까요?')) {
                var unDuplicated = [];
                $.map(selection.selection, function (s, i) {
                    if ($.inArray(s.id, res.data.duplicated) < 0) {
                        unDuplicated.push(s);
                    }
                });
                console.log('Unduplicated Videos: ', unDuplicated);
                callback({ 'selection': unDuplicated })
            }
        } else {
            alert('Server error')
        }
    })
}

SHOW.fn.getCategoryByAppId = function (appId, callback) {
    $.ajax({
        type: 'GET',
        url: '/category/by_appid/' + appId,
        success: function (res) {
            if (res.code == 200) {
                console.log(res)
                callback(res.data);
            } else {
                alert('Server error')
            }
        },
        dataType: 'json',
        async: false
    });
}

SHOW.fn.getCategoryByParentId = function (parentId, callback) {
    $.ajax({
        type: 'GET',
        url: '/category/by_parentid/' + parentId,
        success: function (res) {
            if (res.code == 200) {
                console.log(res)
                callback(res.data);
            } else {
                alert('Server error')
            }
        },
        dataType: 'json',
        async: false
    });
}

SHOW.fn.categoryTypeFormatter = function (value, row, index) {
    return value == 'admin' ? '관리자지정' : '사용자지정';
}

SHOW.fn.videoTitleFormatter = function (value, row, index) {
    return $.base64.decode(value);
}

SHOW.node(function () {
    "use strict"; jQuery.base64 = (function ($) { var _PADCHAR = "=", _ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", _VERSION = "1.0"; function _getbyte64(s, i) { var idx = _ALPHA.indexOf(s.charAt(i)); if (idx === -1) { throw "Cannot decode base64" } return idx } function _decode(s) { var pads = 0, i, b10, imax = s.length, x = []; s = String(s); if (imax === 0) { return s } if (imax % 4 !== 0) { throw "Cannot decode base64" } if (s.charAt(imax - 1) === _PADCHAR) { pads = 1; if (s.charAt(imax - 2) === _PADCHAR) { pads = 2 } imax -= 4 } for (i = 0; i < imax; i += 4) { b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6) | _getbyte64(s, i + 3); x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255, b10 & 255)) } switch (pads) { case 1: b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12) | (_getbyte64(s, i + 2) << 6); x.push(String.fromCharCode(b10 >> 16, (b10 >> 8) & 255)); break; case 2: b10 = (_getbyte64(s, i) << 18) | (_getbyte64(s, i + 1) << 12); x.push(String.fromCharCode(b10 >> 16)); break }return x.join("") } function _getbyte(s, i) { var x = s.charCodeAt(i); if (x > 255) { throw "INVALID_CHARACTER_ERR: DOM Exception 5" } return x } function _encode(s) { if (arguments.length !== 1) { throw "SyntaxError: exactly one argument required" } s = String(s); var i, b10, x = [], imax = s.length - s.length % 3; if (s.length === 0) { return s } for (i = 0; i < imax; i += 3) { b10 = (_getbyte(s, i) << 16) | (_getbyte(s, i + 1) << 8) | _getbyte(s, i + 2); x.push(_ALPHA.charAt(b10 >> 18)); x.push(_ALPHA.charAt((b10 >> 12) & 63)); x.push(_ALPHA.charAt((b10 >> 6) & 63)); x.push(_ALPHA.charAt(b10 & 63)) } switch (s.length - imax) { case 1: b10 = _getbyte(s, i) << 16; x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 63) + _PADCHAR + _PADCHAR); break; case 2: b10 = (_getbyte(s, i) << 16) | (_getbyte(s, i + 1) << 8); x.push(_ALPHA.charAt(b10 >> 18) + _ALPHA.charAt((b10 >> 12) & 63) + _ALPHA.charAt((b10 >> 6) & 63) + _PADCHAR); break }return x.join("") } return { decode: _decode, encode: _encode, VERSION: _VERSION } }(jQuery));

    $('.search-save-category-target-modal').on('click', function () {
        var selection = { 'selection': $('#show-table').bootstrapTable('getSelections') };
        if (!selection.selection.length) {
            alert('선택된 비디오가 없습니다.');
            return;
        }
        SHOW.fn.findVideo(selection, function (selection) {
            if (!selection.selection.length) {
                alert('중복건을 제외하면 저장할 비디오가 없습니다.');
                return;
            }
            var frm = $('#targetAppCategory form').get(0);
            selection.category = {
                app: frm.app.value,
                category: frm.children.value ? frm.children.value : frm.parent.value
            }
            if (!frm.appType.value) {
                alert('앱타입을 선택하세요');
                return;
            } else if (!frm.app.value) {
                alert('앱이름을 선택하세요');
                return;
            } else if (!frm.parent.value) {
                alert('1차 카테고리를 선택하세요');
                return;
            } else if (!frm.children.value) {
                if (!confirm('2차 카테고리를 선택하지 않고 저장할까요')) {
                    return;
                }
            }
            $.post('/data/save', selection, function (res) {
                if (res.code == 200) {
                    alert('저장되었습니다.')
                } else {
                    alert('Server error')
                }
                $('#targetAppCategory').modal('hide')
            })
        });
    })

    $('.video-movecopy-category-target-modal').on('click', function () {
        var frm = $('#moveOrCopyModal form').get(0)
        if (!frm.moveOrCopy.value) {
            alert('작업유형을 선택하세요');
            return;
        } else if (!frm.appType.value) {
            alert('앱타입을 선택하세요');
            return;
        } else if (!frm.app.value) {
            alert('앱이름을 선택하세요');
            return;
        } else if (!frm.parent.value) {
            alert('1차 카테고리를 선택하세요');
            return;
        } else if (!frm.children.value) {
            if (!confirm('2차 카테고리를 선택하지 않고 저장할까요')) {
                return;
            }
        }
        $.post('/data/moveorcopy', {
            moveOrCopy: frm.moveOrCopy.value,
            videos: $('#show-table').bootstrapTable('getSelections'),
            category: {
                app: frm.app.value,
                category: frm.children.value ? frm.children.value : frm.parent.value
            }
        }, function (res) {
            if (res.code == 200) {
                alert((frm.moveOrCopy.value == 'move' ? '이동' : '복사') + ' 되었습니다');
                $('#moveOrCopyModal').modal('hide')
                $('#show-table').bootstrapTable('refresh')
            } else {
                alert('Server error')
            }
        }, 'json')
    });

    $('.app-type-select').on('change', function (e) {
        if (this.value) {
            $.ajax({
                type: 'POST',
                url: '/app/all',
                data: { typeid: this.value },
                success: function (res) {
                    if (res.code == 200) {
                        var s = $('.app-name-select');
                        s.find('option').slice(1).remove();
                        var op = s.find('option').eq(0)
                        for (var i in res.data) {
                            var a = op.clone();
                            a.text(res.data[i].name)
                            a.attr('value', res.data[i].id);
                            s.append(a)
                        }
                    }
                },
                dataType: 'json',
                async: false
            });
        }
    })

    $('.app-name-select').on('change', function (e) {
        if (this.value) {
            SHOW.fn.getCategoryByAppId(this.value, function (data) {
                var s = $('.category-parent-select');
                s.find('option').slice(1).remove();
                var op = s.find('option').eq(0)
                for (var i in data) {
                    var a = op.clone();
                    a.text(data[i].name)
                    a.attr('value', data[i].id);
                    s.append(a)
                }
            })
        }
    })

    $('.category-parent-select').on('change', function (e) {
        if (this.value && $('.category-children-select').length) {
            SHOW.fn.getCategoryByParentId(this.value, function (data) {
                var s = $('.category-children-select');
                s.find('option').slice(1).remove();
                var op = s.find('option').eq(0)
                for (var i in data) {
                    var a = op.clone();
                    a.text(data[i].name)
                    a.attr('value', data[i].id);
                    s.append(a)
                }
            })
        }
    })

    $('.category-edit-modal-save').on('click', function () {
        var frm = $('#categoryEditModal form');
        $('#show-table').bootstrapTable('showLoading');
        frm.ajaxForm({
            url: '/category/' + (frm.get(0).id.value ? 'update' : 'save'),
            dataType: 'json',
            success: function (res) {
                if (res.code == 200) {
                    alert("저장되었습니다.");
                } else {
                    alert(res.message);
                }
                $('#show-table').bootstrapTable('refresh');
                $('#categoryEditModal').modal('hide')
            }
        }).submit();
    })

    $('.show-default-modal').on('hidden.bs.modal', function () {
        $(this).find('form').get(0).reset();
    })
    SHOW.node('#show-table').on('click-row.bs.table', function (e, row, $element) {
        SHOW.var.tableRowSelectedIndex = $element.index();
    });
    $('.app-edit-modal-save').on('click', function (e) {
        var frm = $('.show-default-modal form').get(0);
        if (frm.id.value) {
            var row = $('#show-table').bootstrapTable('getSelections')[0];
            row.name = frm.name.value;
            row.appType = frm.appType.value;
            row.description = frm.description.value;
            row.status = frm.status.value;
            row.developer = frm.developer.value;
            $('#show-table').bootstrapTable('updateRow', { index: SHOW.var.tableRowSelectedIndex, row: row })
            $('.show-modify-select').val('editsave').trigger('change')
            $('.show-default-modal').modal('hide')
        } else {
            $.post($('#show-table').data('save-url'), { 'name': frm.name.value, 'description': frm.description.value, 'apptype': frm.appType.value, 'status': frm.status.value, 'developer': frm.developer.value }, function (res) {
                if (res.code == 200) {
                    alert('저장되었습니다.')
                    frm.reset();
                    $('#show-table').bootstrapTable('refresh');
                    $('.show-default-modal').modal('hide')
                } else {
                    alert('Server error')
                }
            }, 'json')
        }
    })

    $('.apptype-edit-modal-save').on('click', function (e) {
        var frm = $('.show-default-modal form').get(0);
        if (frm.id.value) {
            var row = $('#show-table').bootstrapTable('getSelections')[0];
            row.name = frm.name.value;
            row.description = frm.description.value;
            $('#show-table').bootstrapTable('updateRow', { index: SHOW.var.tableRowSelectedIndex, row: row })
            $('.show-modify-select').val('editsave').trigger('change')
            $('.show-default-modal').modal('hide')
        } else {
            $.post($('#show-table').data('save-url'), { 'name': frm.name.value, 'description': frm.description.value }, function (res) {
                if (res.code == 200) {
                    alert('저장되었습니다.')
                    frm.reset();
                    $('#show-table').bootstrapTable('refresh');
                    $('.show-default-modal').modal('hide')
                } else {
                    alert('Server error')
                }
            }, 'json')
        }
    })

    $('.developer-edit-modal-save').on('click', function (e) {
        var frm = $('#developerEditModal form').get(0);
        if (frm.id.value) {
            var row = $('#show-table').bootstrapTable('getSelections')[0];
            row.name = frm.name.value;
            row.description = frm.description.value;
            $('#show-table').bootstrapTable('updateRow', { index: SHOW.var.tableRowSelectedIndex, row: row })
            $('.show-modify-select').val('editsave').trigger('change')
            $('.show-default-modal').modal('hide')
        } else {
            $.post($('#show-table').data('save-url'), { 'name': frm.name.value, 'description': frm.description.value }, function (res) {
                if (res.code == 200) {
                    alert('저장되었습니다.')
                    frm.reset();
                    $('#show-table').bootstrapTable('refresh');
                    $('#developerEditModal').modal('hide')
                } else {
                    alert('Server error')
                }
            }, 'json')
        }
    })

    $('.show-modify-select').on('change', function (e) {
        var control = this;
        var basepath = $(this).data('basepath');
        var data = $('#show-table').bootstrapTable('getSelections');
        if (data.length) {
            if (this.value == 'edit') {
                var frm = $('.show-default-modal form').get(0);
                frm.id.value = data[0].id;
                if (data[0].name) frm.name.value = data[0].name;
                if (data[0].appType) {
                    frm.appType.value = data[0].appType;
                    if (frm.appType.tagName.toLowerCase() == 'select') {
                        $(frm.appType).trigger('change');
                    }
                }
                if (data[0].description) frm.description.value = data[0].description;
                if (data[0].status) frm.status.value = data[0].status;
                if (data[0].developer) frm.developer.value = data[0].developer;


                if (data[0].app && frm.app) {
                    frm.app.value = data[0].app;
                    if (frm.app.tagName.toLowerCase() == 'select') {
                        $(frm.app).trigger('change');
                    }
                }

                if (data[0].parent && frm.parent) frm.parent.value = data[0].parent;
                if (data[0].type && frm.type) frm.type.value = data[0].type;

                if (data[0].title && frm.title) frm.title.value = data[0].title;

                $('.show-default-modal').modal('show');
                this.selectedIndex = 0;
            } else if (this.value == 'moveorcopy') {
                $('#moveOrCopyModal').modal('show');
            } else if (this.value) {
                $('#show-table').bootstrapTable('showLoading');

                if (($("#editVideoModal").data('bs.modal') || {}).isShown) {
                    $.map(data, function (row, i) {
                        data[i].title = row.title.replace(/[\u{1f300}-\u{1f5ff}\u{1f900}-\u{1f9ff}\u{1f600}-\u{1f64f}\u{1f680}-\u{1f6ff}\u{2600}-\u{26ff}\u{2700}-\u{27bf}\u{1f1e6}-\u{1f1ff}\u{1f191}-\u{1f251}\u{1f004}\u{1f0cf}\u{1f170}-\u{1f171}\u{1f17e}-\u{1f17f}\u{1f18e}\u{3030}\u{2b50}\u{2b55}\u{2934}-\u{2935}\u{2b05}-\u{2b07}\u{2b1b}-\u{2b1c}\u{3297}\u{3299}\u{303d}\u{00a9}\u{00ae}\u{2122}\u{23f3}\u{24c2}\u{23e9}-\u{23ef}\u{25b6}\u{23f8}-\u{23fa}]/ug, function (match) {
                            return match.replace(/[\s\S]/g, function (escape) {
                                return '\\u' + ('0000' + escape.charCodeAt().toString(16)).slice(-4);
                            });
                        })
                    })
                }

                $.post(basepath + (this.value == 'delete' ? 'delete' : 'update'), { 'selection': data }, function (res) {
                    if (res.code == 200) {
                        alert((control.value == 'delete' ? '삭제되었습니다.' : '변경되었습니다.'))
                        $('#show-table').bootstrapTable('refresh');
                    } else {
                        alert('Server error');
                        $('#show-table').bootstrapTable('hideLoading');
                    }
                    control.selectedIndex = 0;
                }, 'json')
            }
        } else {
            alert('작업할 항목을 선택하세요')
            this.selectedIndex = 0;
        }
    })

    $('.box-header-toggle').on('click', function () {
        $('.box-body, .box-footer').slideToggle();
    })
    $('#previewModal').on('shown.bs.modal', function (e) {

        // set the video src to autoplay and not to show related video. Youtube related video is like a box of chocolates... you never know what you're gonna get
        $("#previewModal .video").attr('src', SHOW.var.videoSrc + "?autoplay=1&amp;modestbranding=1&amp;showinfo=0");
    })

    // stop playing the youtube video when I close the modal
    $('#previewModal').on('hide.bs.modal', function (e) {
        // a poor man's stop video
        $("#previewModal .video").attr('src', SHOW.var.videoSrc);
    })

    SHOW.node('.btn-youtube-search').on('click', function () {
        var frm = SHOW.node('.form-youtube-search').get(0);
        $('#show-table').bootstrapTable('showLoading')
        $.post('/data/search', { 'mode': $(frm.mode).val(), 'keyword': frm.keyword.value, 'id': frm.id.value }, function (res) {
            if (res.code == 200) {
                if (res.data.length) {
                    $('#show-table').bootstrapTable('destroy')
                    $('#show-table').bootstrapTable({
                        'data': res.data
                    }).on('page-change.bs.table', function () {
                        console.log('Video Preview button Event initialized')
                        $('.video-btn').click(function () {
                            SHOW.var.videoSrc = $(this).data("src");
                            console.log(SHOW.var.videoSrc)
                        });
                    });
                    $('.video-btn').click(function () {
                        SHOW.var.videoSrc = $(this).data("src");
                        console.log(SHOW.var.videoSrc)
                    });
                    $('#show-table').bootstrapTable('hideLoading')
                    $('button.btn-box-tool .fa').trigger('click')
                    SHOW.var.youtubeSearchRetry = 0;
                } else if (SHOW.var.youtubeSearchRetry < 3) {
                    SHOW.var.youtubeSearchRetry++;
                    SHOW.node('.btn-youtube-search').trigger('click')
                } else {
                    SHOW.var.youtubeSearchRetry = 0;
                    $('#show-table').bootstrapTable('hideLoading')
                    $('#show-table').bootstrapTable('removeAll')
                    /*alert('가용한 API 키가 없거나 재로그인 하세요')
                    if(confirm('재로그인?')) {
                        location.href = '/sign/logout';
                    }*/
                }
            }
        }, 'json')
    })
    SHOW.node('#show-table').bootstrapTable().on('load-success.bs.table', function () {
        $('.video-btn').click(function () {
            SHOW.var.videoSrc = $(this).data("src");
            console.log(SHOW.var.videoSrc)
        });

        $('.category-subsidiary').click(function () {
            var options = SHOW.node('#show-table').bootstrapTable('getOptions');
            var parentId = $(this).data('parent');
            options.queryParams = function (a) {
                var params = { 'keyword': SHOW.node('input[name=keyword]').val(), 'parentId': parentId }
                if (SHOW.node('.video-list-app-select').length) {
                    if (SHOW.node('.video-list-app-select').val()) {
                        params.appid = SHOW.node('.video-list-app-select').val();
                    }
                }
                return $.extend(a, params)
            }
            SHOW.node('#show-table').bootstrapTable('destroy').bootstrapTable(options)
        });
    });

    SHOW.node('.form-youtube-search input[name=keyword]').on('keyup', function (e) {
        if (e.keyCode == 13) {
            SHOW.node('.btn-youtube-search').trigger('click')
        }
    })
    SHOW.node('.keyword-search-btn').on('click', function () {
        //if(SHOW.node('input[name=sword]').val()) {
        var options = SHOW.node('#show-table').bootstrapTable('getOptions');
        options.queryParams = function (a) {
            var params = {
                'keyword': SHOW.node('input[name=keyword]').val(),
                'app': $('.app-select').val(),
                'category_type': $('.category-type-select').val()
            }
            if (SHOW.node('.video-list-app-select').length) {
                if (SHOW.node('.video-list-app-select').val()) {
                    params.appid = SHOW.node('.video-list-app-select').val();
                }
            }
            if (SHOW.node('.video-list-category-select').length) {
                if (SHOW.node('.video-list-category-select').last().val()) {
                    params.category = SHOW.node('.video-list-category-select').last().val();
                }
            }
            return $.extend(a, params)
        }
        SHOW.node('#show-table').bootstrapTable('destroy').bootstrapTable(options)
        //}
    })

    SHOW.node('.keyword-search-input').on('keyup', function (e) {
        if (e.keyCode == 13) {
            SHOW.node('.keyword-search-btn').trigger('click')
        }
    })

    SHOW.node('.youtube-search-mode-select').on('change', function () {
        switch (this.value) {
            case 'search.list':
                SHOW.node('.youtube-search-keyword').prop('disabled', false).focus();
                SHOW.node('.youtube-search-id').prop('disabled', true);
                break;
            case 'search.channel.ID':
            case 'search.channel.Name':
                SHOW.node('.youtube-search-keyword').prop('disabled', false).focus();
                SHOW.node('.youtube-search-id').prop('disabled', false);
                break;
            case 'playlist.ID':
                SHOW.node('.youtube-search-keyword').prop('disabled', true);
                SHOW.node('.youtube-search-id').prop('disabled', false).focus();
                break;
            default:
                SHOW.node('.youtube-search-keyword').prop('disabled', false).focus();
                SHOW.node('.youtube-search-id').prop('disabled', true)
                break;
        }
    })

    SHOW.node('.upload-modal-save').on('click', function () {
        SHOW.node('#uploadModal form').submit();
    })
    SHOW.node('#uploadModal form').ajaxForm({
        dataType: 'json',
        success: function (res) {
            if (res.code == 200) {
                alert('업로드 완료')
            } else {
                alert('오류');
            }
            $('#show-table').bootstrapTable('refresh');
            $('#uploadModal').modal('hide')
        }
    });

    SHOW.node('.video-edit-modal').on('click', function () {
        var frm = SHOW.node('#editVideoModal form').get(0);
        if (frm.id.value) {
            var row = $('#show-table').bootstrapTable('getSelections')[0];
            row.title = frm.title.value;
            row.description = frm.description.value;
            $('#show-table').bootstrapTable('updateRow', { index: SHOW.var.tableRowSelectedIndex, row: row })
            $('.show-modify-select').val('editsave').trigger('change')
            $('.show-default-modal').modal('hide')
        }
    })

    if (SHOW.node('.all-video-list').length) {
        SHOW.node('.all-video-list').data('url', '/data')
        SHOW.node('.keyword-search-btn').trigger('click')
    }

    SHOW.node('.show-export-excel').on('click', function () {
        var videos = $.map($('#show-table').bootstrapTable('getSelections'), function (row, i) {
            return row.id
        });
        SHOW.node('.export-hide').find('input').val(videos.join(',')).parent().submit();
    })
})

