
    if (typeof (conf) === 'undefined') {
        var conf = {
            form: 'form_'
        }
    }

    function InitDatatable() {
            $('#datatable-1').on('xhr.dt', function (e, settings, json) {
                    if (typeof (json.data) == 'object' && json.data.length >0) {
                        for (var i in json.data) {
                            var id = json.data[i].id;
                            var name = json.data[i].name;
                            var status = json.data[i].status;
                            var accessed = json.data[i].accessed;
                            var path = json.data[i].path;
                            var tasks = json.data[i].tasks;

                            json.data[i].path = "<a href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/edit-video?step=4&id="+ id +"' data-fieldname='path'>"+ json.data[i].path +"</a>";

                            json.data[i].operations = "<div class='col-xs-3 col-sm-8'>\n\
                                                            <a href='#' class='dropdown-toggle no_context_menu' data-toggle='dropdown'>\n\
                                                                <i class='pull-right fa fa-cog'></i>\n\
                                                            </a>\n\
                                                            <ul class='dropdown-menu pull-right'>\n\
                                                                <li>\n\
                                                                    <a href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/edit-video?id="+id+"'>\n\
                                                                        <span>{{ 'Edit'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n\
                                                                <li>\n\
                                                                    <a class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/" + (accessed!=0 ?"disable":"enable")+"-video' data-videoid='"+id+"'>\n\
                                                                        <span>" + ( accessed ? "{{ 'Unpublish'|trans }}": "{{ 'Publish'|trans }}") + "</span>\n\
                                                                    </a>\n\
                                                                </li>\n\
                                                                <li>\n\
                                                                    <a class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/create-tasks' data-videoid='"+id+"'>\n\
                                                                        <span>{{ 'Create task'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n\
                                                                <li>\n\
                                                                    <a class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-info' data-videoid='" + id + "'>\n\
                                                                        <span>{{ 'Check file'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n";
                            if (json.data[i].complaints) {
                                json.data[i].operations +=      "<li>\n\
                                                                    <a class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/reset-video-claims' data-videoid='"+id+"'>\n\
                                                                        <span>{{ 'Reset media-claims'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n";
                            }
                            json.data[i].operations +=       "<li>\n\
                                                                    <a href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-logs?video_id="+id+"'>\n\
                                                                        <span>{{ 'Activity log'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n\
                                                                <li>\n\
                                                                    <a class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/remove-video' data-videoid='"+id+"' data-videoname='"+name+"'>\n\
                                                                        <span>{{ 'Remove'|trans }}</span>\n\
                                                                    </a>\n\
                                                                </li>\n\
                                                            </ul>\n\
                                                        </div>";

                            if (json.data[i]['added'] != 0) {
                                var dateOn = new Date(json.data[i]['added']);
                                json.data[i]['added'] = dateOn.toLocaleFormat("%b %d, %Y").replace(" ", "&nbsp;");
                            }

                            json.data[i].name = "<a href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/edit-video?id=" + id + "' data-fieldname='name'>" +escapeHtml( json.data[i].name )+ "</a>";
                            json.data[i].o_name = escapeHtml( json.data[i].o_name );

                            json.data[i].is_series = json.data[i].is_series ? '<i class="fa fa-circle"></i>': "";

                            json.data[i].cat_genre = '<div class="nowrap flexible"><span class="" title="' +json.data[i].cat_genre+ '">' +escapeHtml( json.data[i].cat_genre )+ '</span></div>';


                            var taskStr = '';
                            var msgClass = '';
                            var taskStatus = '';
                            if (typeof(tasks) == 'object' && tasks.length > 0) {
                                var itemCounter = tasks.length - 1;
                                for (var num in tasks) {
                                    var endDate = new Date(tasks[num]['end_time']);
                                    taskStatus = "{{'Open'|trans}}";

                                    if (tasks[num]['ended'] || tasks[num]['rejected'] ) {
                                        msgClass += " line-through ";
                                        if (tasks[num]['rejected'] ) {
                                            msgClass += " txt-warning ";
                                            taskStatus = "{{'Rejected'|trans}}";
                                        } else if (tasks[num]['ended'] != 0 ) {
                                            taskStatus = "{{'Done'|trans}}";
                                        }
                                    } else if (tasks[num]['expired']){
                                        msgClass += " txt-danger ";
                                        taskStatus = "{{'Expired'|trans}}";
                                    }

                                    taskStr += '<a title="'+ taskStatus+ '" class="' + msgClass + '" href="{{ app.request_context.baseUrl }}/tasks/task-detail-video?id=' + tasks[num]['id']+ '">№' + tasks[num]['id'] + (!(tasks[num]['ended'] || tasks[num]['rejected']) && tasks[num]['end_time'] ? ' ({{ 'ending'|trans }} ' + endDate.toLocaleFormat("%d-%m-%Y") + ')': '') + '</a>' + (num != itemCounter?', ': '');
                                    msgClass = '';
                                }
                            } else {
                                //taskStr = "{{ 'No tasks'|trans }}";
                                taskStr = "-";
                            }
                            json.data[i].tasks = taskStr;

                            json.data[i].complaints = '';
                            if (json.data[i].video_counter) {
                                json.data[i].complaints += (" {{ 'video'|trans }} - " + json.data[i].video_counter);
                            }

                            if (json.data[i].sound_counter) {
                                json.data[i].complaints += (" {{ 'sound'|trans }} - " + json.data[i].sound_counter);
                            }
                            if (!json.data[i].complaints) {
                                json.data[i].complaints = "0"
                            }

                            if (json.data[i]['task_date_on'] != 0) {
                                var dateOn = new Date(json.data[i]['task_date_on']);
                            }
                            json.data[i].accessed = (accessed != 0 ? "<i data-toggle='tooltip' class='fa icon icon-eye' title='{{ 'Published' |trans }}'></i>" : ((typeof(json.data[i].task_id) != 'undefined' && json.data[i].task_id) ? "<i data-toggle='tooltip' class='fa icon icon-calendar' title='{{ 'Scheduled' |trans }} " +dateOn.toLocaleFormat("%b %d, %Y")+ "'></i>" : "<i data-toggle='tooltip' class='fa icon icon-eye-slash' title='{{ 'Unpublished' |trans }}'></i>"));

                            if (json.data[i].media_status || (!json.data[i].media_url && json.data[i].status)) {
                                json.data[i].accessed += "<i data-toggle='tooltip' class='fa icon icon-archive' title='{{ 'Available on storages'|trans }}'></i>";
                            } else if (!json.data[i].media_url) {
                                json.data[i].accessed += "<i data-toggle='tooltip' class='fa icon icon-banned' title='{{ 'Not available on storages'|trans }}. {{ 'Check file'|trans }}'></i>";
                            }

                            if (json.data[i].media_url) {
                                json.data[i].accessed += "<i data-toggle='tooltip' class='fa icon icon-link' title='{{ 'Available by custom URL'|trans }}'></i>";
                            }

                        }
                    }
                }).dataTable({
                "processing": true,
                "serverSide": true,
                "ajax": {
                    "url": "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-list-json"
                },
                "language": {
                    "url": "{{ app.datatable_lang_file }}"
                },

                //from macro
                "columns": [
                    // be sure to change col indexes at aoColumnDefs if added
                    { "data": null, defaultContent: "", orderable: false, /*visible: true,*/ className: 'w-1p select-checkbox'},
                {% for key, item in app['dropdownAttribute'] %}
                    {% if 'all' != item.name %}
                    {"data": "{{ item.name }}", "name": "{{ item.name }}" {% if not(item.checked) %}, visible: false, className: 'none'{% endif %}}{% if not loop.last %},{% endif %}
                    {% endif %}
                {% endfor %}
                ],

                "scrollCollapse": true,
                "bFilter": true,
                "bPaginate": true,
                "lengthChange": true,
                "bInfo":     true,
                "order": [[ 1, "desc" ]],
                "bSort" : true,

                "fixedHeader": {
                    header: true,
                    headerOffset: $('header.navbar').height()
                },
                "select": {
                    style:    'multi',
                    selector: 'td.select-checkbox'
                },
                "rowId": "RowOrder", // required to restore selected rows on reload

                // modify the sDom
                "sDom": "<'clearfix'<'pull-right'fAV><'button-place'B>>rt<'row-fluid'<'col-md-4 no-padding'i><'col-md-8 no-padding'pl>>",

                /* Before shift:
                "aoColumnDefs": [
                    { "targets": [ -1 , 6], "orderable": false},
                    { "searchable": false, "targets": [ 4, 5, 6, 7, 8, 9, 10, 11, -3, -2, -1 ] },
                    { "width": "10%", "targets": [ 1, 2, 3, 6, 8, -2] },
                    { className: "dt-center",    "targets": [ 5 ] },
                    { className: "vc-cat_genre", "targets": [ 6 ] },
                    { className: "dt-status",   "targets": [ -2 ] },
                    { className: "action-menu", "targets": [ -1 ] }
                ]
                */

                "aoColumnDefs": [
                    //{ "targets": [ 7, -1 ], "orderable": false },
                    { "searchable": false, "targets": [ 0, 5, 6, 7, 8, 9, 10, 11, 12, -3, -2, -1 ] },
                    { "sortable": false, "targets": [ 0, 7, -2, -1 ] },
                    { "width": "10%", "targets": [ 2, 3, 4, 7, 9, -2 ] },
                    { className: "dt-center",    "targets": [ 6 ] },
                    { className: "vc-cat_genre", "targets": [ 7 ] },
                    { className: "dt-status dt-nowrap",   "targets": [ -2 ] },
                    { className: "action-menu", "targets": [ -1 ] }
                ],


                "buttons": [

                    // Publish buttons
                    {
                        extend: 'collection',
                        text: '<i class="fa fa-calendar"></i> {{'Publishing'|trans }} <i class="fa fa-caret-down"></i>',
                        autoClose: true,
                        background: true,
                        fade: 0,
                        buttons: [
                            {
                                text: '{{ 'Publish'|trans }}',
                                action: function ( e, dt, node, config ) {
                                    if( $(this).hasClass('disabled') ){
                                        return false;
                                    }

                                    e.stopPropagation();
                                    e.preventDefault();
                                    JScloseModalBox();

                                    // call popup window
                                    setEnableDatePicker( node );

                                }
                            },
                            {
                                text: '{{ 'Unpublish'|trans }}',
                                action: function ( e, dt, node, config ) {
                                    var sendData = {};
                                    var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );

                                    sendData.group_key = "videoid";
                                    sendData.videoid = ids;

                                    if ((sendData.videoid).search(',') != -1){
                                        sendData.videoid = JSON.stringify(sendData.videoid.split(','));
                                    }

                                    ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/disable-video", sendData, false, false, true);

                                }
                            }
                        ]
                    },

                    // Drop Сomplaints button
                    {
                        text: '<i class="fa fa-thumbs-down"></i> {{'Drop сomplaints'|trans }}',
                        action: function ( e, dt, node, config ) {

                            if( $(this).hasClass('disabled') )
                                return false;

                            e.stopPropagation();
                            e.preventDefault();
                            JScloseModalBox();

                            var sendData = {};
                            var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );

                            sendData.group_key = "videoid";
                            sendData.videoid = ids;

                            if ((sendData.videoid).search(',') != -1){
                                sendData.videoid = JSON.stringify(sendData.videoid.split(','));
                            }

                            ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/reset-video-claims", sendData, false, false, true);

                        }
                    },

                    // Delete button
                    {
                        text: '<i class="fa fa-trash"></i> {{'Delete'|trans }}',
                        action: function ( e, dt, node, config ) {

                            if( $(this).hasClass('disabled') )
                                return false;

                            e.stopPropagation();
                            e.preventDefault();
                            JScloseModalBox();

                            var tr = dt.rows( { selected: true } );
                            var sendData = {};
                            var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );

                            if( confirm( "{{"Are you sure you want to delete"|trans}} " +tr.count()+ " {{"video"|trans}}?") ) {
                                sendData.group_key = "videoid";
                                sendData.videoid = ids;

                                if ((sendData.videoid).search(',') != -1){
                                    sendData.videoid = JSON.stringify(sendData.videoid.split(','));
                                }

                                ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/remove-video", sendData, false, false, true);
                                resetTableButtons();
                                setGroupSelectState( "none" );
                            }
                            return false;
                        }
                    }
                ]

            }).prev('.dataTables_processing').hide();
        }

    function InitSelect2() {
        $('#s2_video_moderators').select2({minimumResultsForSearch: -1, dropdownAutoWidth: false, width: '100%'});
    }

    function yelp() {
        $(document).ready(function () {
            
            LoadDataTablesScripts(InitDatatable);
            LoadSelect2Script(InitSelect2);

            $(document).tooltip({
                selector: '[data-toggle="tooltip"]',
                placement: 'top'
            });

            var table = $('#datatable-1').DataTable();

            table
                .on( 'select', function ( e, dt, type, indexes ) {

                    var rows = dt.rows( { selected: true } ).count();
                    
                    $(".dt-buttons .dt-button").show().removeClass( "disabled" );

                    if ( rows == dt.rows().count() ){
                        setGroupSelectState( "all" );
                    } else {
                        setGroupSelectState( "some" );
                    }

                } )
                .on( 'deselect', function ( e, dt, type, indexes ) {

                    var rows = dt.rows( { selected: true } ).count();
                    
                    if ( rows >= 1 ) {
                        $(".dt-buttons .dt-button").show().removeClass( "disabled" );
                        setGroupSelectState( "some" );
                    } else if ( rows == 0 ) {
                        setGroupSelectState( "none" );
                        resetTableButtons();
                    }

                } )

                // expand Processing width for overflow table
                .on( 'processing.dt', function ( e, settings, processing ) {
                    $(settings.aanFeatures.r).css( 'width', $(settings.aanFeatures.t).width() );
                } );

                // reset Buttons on Paging reload 
                $('#datatable-1').on( 'page.dt', function () {
                    resetTableButtons( );
                    setGroupSelectState( "none" );
                } );

                // Reinit group actions Table Buttons
                $('#datatable-1').on( 'draw.dt', function ( e, settings ) {
                    if( table.rows( { selected: true } ).ids().length == 0 ) {
                        resetTableButtons(); 
                        setGroupSelectState('none');
                    }
                } );


            // Select dropdowns 
            $( "#select_all" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    table.rows().select();
                }
            });

            $( "#select_none" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    table.rows().deselect();
                }
            });

            $( "#select_inverse" ).click( function(e){
                if( !$(this).hasClass("disabled") ) {
                    var rowsSelected = table.rows( { selected: true } );
                    table.rows().select();
                    rowsSelected.deselect();
                }
            });

            // Disable annoying message on disabled buttons
            $(document).off('click', "a[disabled], a.disabled");

            setTimeout( initTableButtons, 200 );

            
            $(document).on('click', "a.main_ajax", function (e) {
                e.stopPropagation();
                e.preventDefault();
                var _this = $(this);
                $(_this).closest('.open').removeClass('open');

                if( $(this).attr("href").indexOf("remove-video") != -1 && !confirm("{{"Delete video"|trans}} \"" +$(this).data("videoname")+ "\"?") ) {
                    return;
                }

                if (_this.attr('href').search("enable") != -1 && !_this.data('video_on_date')) {
                    setEnableDatePicker(_this);
                    return false;
                }

                if (_this.attr('href').search("create-tasks") != -1 && !_this.data('sendData')) {
                    showTaskForm(_this);
                    return false;
                }
                ajaxPostSend($(this).attr('href'), $(this).data(), false, false);

                return false;
            });

            $(document).on('click', "#apply_enable_date", function(e){
                e.stopPropagation();
                e.preventDefault();

                // single Publishing
                var link = $("a[data-videoid='" + $("#modalbox input[name='link_id']").val() + "'][href*='enable']");
                link.data('video_on_date', $("#modalbox input[name='video_on_date']").val());
                
                // some outdated code
                if ($("#modalbox input[name='empty_confirm']").length !=0) {
                    link.data('empty_confirm', 1);
                }

                link.trigger('click');

                return false;
            });

            $(document).on('click', "#apply_enable_date_group", function(e){
                e.stopPropagation();
                e.preventDefault();

                // group Publishing
                if( $("#modalbox input[name='video_on_date']").val() != '' && table.rows({ selected: true }) ){ 

                    var sendData = {};
                    var ids = table.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );
                
                    sendData.group_key = "videoid";
                    sendData.videoid = ids;
                    sendData.video_on_date = $("#modalbox input[name='video_on_date']").val();

                    if ((sendData.videoid).search(',') != -1){
                        sendData.videoid = JSON.stringify(sendData.videoid.split(','));
                    }

                    ajaxPostSend( "{{app.request_context.baseUrl}}/{{ app.controller_alias }}/enable-video", sendData);
                }

                return false;
            });

            $(document).on('click', "#reset_enable_date, #modalbox, #modalbox a.close-link, #modalbox a.close-link *", function(e){
                if (e.currentTarget != e.target) {
                    return;
                }
                e.stopPropagation();
                e.preventDefault();
                $("div[id*='datepicker']").hide().remove();
                closeModalBox();
                return false;
            });
            
            $(document).on('click', "#modalbox_ad button[type='submit']", function (e) {
                var sendData = {
                    id: $("#modalbox_ad input[name='id']").val(),
                    to_usr: $("#modalbox_ad select").val(),
                    comment: $("#modalbox_ad textarea").val()
                };
                
                e.stopPropagation();
                e.preventDefault();
                var linkObj = $("a[data-videoid='" + $("#modalbox_ad input[type='hidden']").val() + "'][href*='create']");
                
                linkObj.data('sendData', sendData).click();
                return false;
            });

            $(document).off('click', "#modalbox_ad a.close-link, #modalbox_ad a.close-link .fa-times, #modalbox_ad, #modalbox_ad button[type='reset']");
            $(document).on('click', "#modalbox_ad a.close-link, #modalbox_ad a.close-link .fa-times, #modalbox_ad, #modalbox_ad button[type='reset']", function (e) {
                if (e.target != e.currentTarget) {
                    return;
                }
                e.stopPropagation();
                e.preventDefault();
                $("#modalbox_ad").hide();

                $("input, select, textarea", "#modalbox_ad").val('');
                $("#modalbox_ad select").select2('destroy');
                $("#modalbox_ad form").get(0).reset();
                InitSelect2();
                return false;
            })
        });
    }

    document.addEventListener("DOMContentLoaded", yelp, false);

    var setMD5 = function(){
        $("#modalbox a[href$='get-md5']").replaceWith('<span class="txt-success"> &nbsp; {{ 'counting'|trans }} &nbsp; </span>');
    };

    var setMD5Error = function(obj){
        if (obj.error) {
            $("#modalbox a[href$='get-md5']").replaceWith('<span class="txt-danger"> &nbsp;' + obj.error + '&nbsp; </span>');
        }
    };

    var videoinfo = function (obj){
        closeModalBox();
        $('#modalbox').show();
        $('#modalbox').find('.modal-header-name span').text(obj.title);
        var baseInfo = obj.base_info;
        if (typeof(baseInfo) == 'string') {
            $('#modalbox').find('.devoops-modal-inner').append('<div class="col-xs-12"><span>' + baseInfo + '</span></div>');
        } else if (typeof(baseInfo) == 'object') {
            var table = $('<table class="video_info"></table>').appendTo($('#modalbox').find('.devoops-modal-inner'));
            table.append('<tr><td>{{ 'Server'|trans }}</td><td>{{ 'Catalogue'|trans }}</td><td>{{ 'Episodes'|trans }}</td><td>&nbsp;</td></tr>');
            table.wrap('<div class="col-xs-12"></div>');
            $.each(baseInfo, function(index, value){
                var trStr = '<tr><td>'+ value.storage_name +'</td><td>'+ value.path +'</td><td>'+ value.series +'</td>';
                    trStr += '<td><a class="main_ajax no_context_menu" href="{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-md5">{{ 'Calculate MD5 checksum'|trans }}</a></td></tr>';
                table.append(trStr);
                table.find('a').data('storage_name', value.storage_name);
                table.find('a').data('media_name', value.path);
                if (value.files.length > 0 ) {
                    var filesStr = '';
                    var md5Str = '';
                    $.each(value.files, function(f_index, f_value){
                        filesStr = '<span class="video_file_name">' + f_value.name + '</span>';
                        md5Str = '<span class="video_file_name">' + f_value.md5 + '</span>';
                        table.append('<tr><td colspan="3">' + filesStr + '</td><td >' + md5Str + '</td></tr>');
                    });
                }
            });
        }
    };

    function closeModalBox(){
        $("#modalbox").hide().removeClass("modal-schedule");
        $(".datepicker-inline").datepicker( "destroy" );
        $('#modalbox').find('.modal-header-name span').empty();
        $('#modalbox').find('.devoops-modal-inner').empty();
        $('#modalbox').find('.devoops-modal-bottom').empty();
    }

    function setEnableDatePicker(obj){
        $('#modalbox').find('.modal-header-name span').text('{{ 'Publish'|trans }}');

        $('#modalbox').find('.devoops-modal-inner').html('\n\
                <div class="box-content">\n\
                    <form class="form-horizontal" role="form">\n\
                        <div class="form-group">\n\
                            <div class="col-xs-10 col-sm-12">\n\
                                <span class="col-xs-8 col-sm-12">\n\
                                   <input type="hidden" name="link_id" value="' + obj.data('videoid') + '">\n\
                                   <input type="hidden" data-date-format="dd-mm-yy" name="video_on_date">\n\
                                   <input type="text" id="video_on_date" class="form-control own_fields datepicker-field" data-date-format="dd-mm-yy" readonly="readonly">\n\
                                   <div class="datepicker-inline" data-date-format="dd-mm-yy"></div>\n\
                                    <div class="bg-danger"></div>\n\
                                </span>\n\
                            </div>\n\
                        </div>\n\
                    </form>\n\
                </div>');
				

		$('#modalbox').find('.devoops-modal-bottom').html('<div class="pull-right no-padding">&nbsp;</div>\n\
                        <div class="pull-right no-padding">\n\
                            <button type="submit" id="apply_enable_date'+(obj.hasClass("main_ajax") ? '':'_group')+'" class="btn btn-success  pull-right">{{ 'Publish'|trans }}</button>\n\
                            <button type="reset" id="reset_enable_date" class="btn btn-default pull-right" >{{ 'Cancel'|trans }}</button>\n\
                        </div>');
   

        $(".datepicker-inline").datepicker({
                language    : 'ru',
                dateFormat  : 'dd-mm-yy',
                firstDay    : 1,
                minDate     : new Date(),
                altField    : "input#video_on_date",
                altFormat   : "MM d, yy",
                currentText : '{{ 'Today'|trans }}', // Today button text
                dayNamesMin : [
                    '{{ 'Sun'|trans }}',
                    '{{ 'Mon'|trans }}',
                    '{{ 'Tue'|trans }}',
                    '{{ 'Wed'|trans }}',
                    '{{ 'Thu'|trans }}',
                    '{{ 'Fri'|trans }}',
                    '{{ 'Sat'|trans }}'
                ],
                dayNames    : [
                    '{{ 'Sunday'|trans }}',
                    '{{ 'Monday'|trans }}',
                    '{{ 'Tuesday'|trans }}',
                    '{{ 'Wednesday'|trans }}',
                    '{{ 'Thursday'|trans }}',
                    '{{ 'Friday'|trans }}',
                    '{{ 'Saturday'|trans }}'
                ],
                monthNames  : [
                    '{{ 'January'|trans }}',
                    '{{ 'February'|trans }}',
                    '{{ 'March'|trans }}',
                    '{{ 'April'|trans }}',
                    '{{ 'May'|trans }}',
                    '{{ 'June'|trans }}',
                    '{{ 'July'|trans }}',
                    '{{ 'August'|trans }}',
                    '{{ 'September'|trans }}',
                    '{{ 'October'|trans }}',
                    '{{ 'November'|trans }}',
                    '{{ 'December'|trans }}'
                ],
                onSelect    : function(dateText){
                                $("input[name=video_on_date]").val( $(this).val() );
                                //alert(dateText);
                            }
            }
        );

        // Rewrite the default behavior of Today Button to select current day
        // https://stackoverflow.com/a/7613795/4704856
        $.datepicker._gotoToday = function(id) {
            var target = $(id);
            var inst = this._getInst(target[0]);
            if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
                    inst.selectedDay = inst.currentDay;
                    inst.drawMonth = inst.selectedMonth = inst.currentMonth;
                    inst.drawYear = inst.selectedYear = inst.currentYear;
            }
            else {
                    var date = new Date();
                    inst.selectedDay = date.getDate();
                    inst.drawMonth = inst.selectedMonth = date.getMonth();
                    inst.drawYear = inst.selectedYear = date.getFullYear();
                    // the below two lines are new
                    this._setDateDatepicker(target, date);
                    this._selectDate(id, this._getDateDatepicker(target));
            }
            this._notifyChange(inst);
            this._adjustDate(target);
        }

        // clear input assigned to Datepicker
        $("input#video_on_date").val("");
        // remove visual select of today in calendar
        $(".ui-datepicker-today .ui-state-active").removeClass("ui-state-active")

        // ?? this will be removed in future
        $("div[id*='datepicker']").addClass('dp_white');
        
        // close context menu before displaying modalbox
        $(obj).closest('div.open').removeClass('open');
        
        // show modal box
        $('#modalbox').addClass("modal-schedule").show();
    }

    function initTableButtons() { 
        //$(".dataTables_wrapper .dt-buttons .dt-button").hide();
        $(".dt-group-select-dropdown").prependTo( $(".dataTables_wrapper .dt-buttons").first() );

        resetTableButtons();
    }

    function resetTableButtons() { 
        $(".dt-buttons .dt-button").not(".dt-group-select-dropdown .dt-button").addClass( "disabled" ).hide();
    }

    function setGroupSelectState(state) {
        if ( typeof state != "string" ){
            return;
        }

        $(".dt-group-select-dropdown").removeClass( "all none some" ).addClass( state );
        
        $("#select_all, #select_none, #select_inverse").removeClass( "disabled" );
            
            switch( state ) {
        
        case "none": $("#select_none, #select_inverse").addClass( "disabled" );
                     break;

        case "all":  $("#select_all").addClass( "disabled" );
                     break;
        }
    }


    function showTaskForm(obj){
        var showName = $(obj).closest('tr').find('a[data-fieldname="name"]').text();
        $('#modalbox_ad').find('input[type="hidden"]').val($(obj).data('videoid')).next().text(showName);
        $('#modalbox_ad').show();
        $('#modalbox_ad textarea').focus();
        $(obj).closest('div.open').removeClass('open');
    }
    
    function hideTaskForm(obj){
        
        $('#modalbox_ad').find('input[type="hidden"]').val('').next().text('');
        $('#modalbox_ad').find('textarea').val('');
        $('#modalbox_ad').hide();
        $(obj).closest('div.open').removeClass('open');
    }

    // some old code
    function publishWarning(obj){
        var sendData = {
            empty_confirm: 1
        };
        $("#modalbox form input").each(function(){
            sendData[$(this).attr('name')] = $(this).val();
        });

        $("#modalbox form").empty();
        var field;
        for (var name in sendData) {
            field = $('<input/>').appendTo("#modalbox form");
            field.prop({type: 'hidden', name: name, value: sendData[name]});
        }
        if (obj && obj.msg) {
            field = $('<span/>').appendTo("#modalbox form");
            field.addClass('col-sm-11').text(obj.msg);
        }

        $(obj).removeData('video_on_date').removeData('empty_confirm');
    }
