
function InitDatatable() {
    $('#datatable-1').on('xhr.dt', function (e, settings, json) {
        if (typeof (json.data) == 'object') {
            var date, id, name, curr_on_date, videoid, taskid, video_on_date = new Date().toLocaleFormat("%d-%m-%Y");
            for (var i in json.data) {
                id = json.data[i].id;
                name = json.data[i].name;
                videoid = json.data[i].video_id;
                taskid = json.data[i].task_id;

                date = json.data[i]['task_added'];
                if (date > 0) {
                    date = new Date(date * 1000);
                    json.data[i]['task_added'] = date.toLocaleFormat("%b %d, %Y %H:%M");
                }

                date = json.data[i]['task_date_on'];
                if (date > 0) {
                    date = new Date(date);
                    json.data[i]['task_date_on'] = "{{ 'scheduled on'|trans }} " + date.toLocaleFormat("%d-%m-%y");
                    curr_on_date = date.toLocaleFormat("%d-%m-%y");
                }

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

                json.data[i].operations = '<div class="col-xs-3 col-sm-8 ddd">\n\
                                                <a href="#" class="dropdown-toggle" 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 class="main_ajax no_context_menu" href="{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/enable-video" data-shedulepage="1" data-videoid="'+videoid+'" data-taskid="'+taskid+'" data-publish_on="'+date.toLocaleFormat("%d-%m-%Y")+'" data-video_on_date="'+video_on_date+'" data-curr_on_date="'+curr_on_date+'" data-rowid = "' + json.data[i].RowOrder +'">\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 }}/enable-video" data-shedulepage="1" data-videoid="'+videoid+'" data-video_on_date="'+video_on_date+'" data-waiting="1"  data-rowid = "' + json.data[i].RowOrder +'">\n\
                                                            <span>{{ 'Publish now'|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-tasks" data-taskid="'+taskid+'"  data-rowid = "' + json.data[i].RowOrder +'">\n\
                                                            <span>{{ 'Remove schedule'|trans }}</span>\n\
                                                        </a>\n\
                                                    </li>\n\
                                                </ul>\n\
                                            </div>';

            }
        }
    }).dataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-schedule-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,
        "bInfo":     true,
        "bSort" : true,
        "lengthChange": 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": [
         { "orderable": false, "targets": [ -1 ] },
         { "searchable": false, "targets": [ -1 ] },
         { "width": "10%", "targets": [ 0, 3, 4, 5 ] },
         //{ "width": "25%", "targets": [ 1, 2 ] },
         { className: "action-menu", "targets": [ -1 ] }
         ],*/

        "order": [[ 1, "asc" ]],

        "aoColumnDefs": [
            { "orderable": false, "targets": [ -1 ] },
            { "searchable": false, "targets": [ -1 ] },
            { "width": "10%", "targets": [ 1, 4, 5, 6 ] },
            //{ "width": "25%", "targets": [ 2, 3 ] },
            { className: "dt-nowrap", "targets": [ 1, -3 ] },
            { className: "action-menu", "targets": [ -1 ] }
        ],


        "buttons": [

            // Publish buttons
            {
                text: '<i class="fa fa-calendar"></i> {{ 'Edit schedule'|trans }}',
                action: function ( e, dt, node, config ) {
                    if( $(this).hasClass('disabled') ){
                        return false;
                    }

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

                    // call popup window
                    setEnableDatePicker( node );

                }
            },

            // Publish Now button
            {
                text: '<i class="fa fa-calendar-check-o"></i> {{'Publish now'|trans }}',
                action: function ( e, dt, node, config ) {

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

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

                    var sendData = {};
                    var today = new Date().toLocaleFormat("%d-%m-%Y");
                    var ids = dt.rows( { selected: true } ).ids().toArray().toString().replace(/dTRow_/g, "" );

                    sendData.group_key = "videoid";
                    sendData.videoid = ids;
                    sendData.video_on_date = today;
                    sendData.shedulepage = 1;

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

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

                    resetTableButtons();
                    setGroupSelectState( "none" );
                }
            },

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

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

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

                    var sendData = {};
                    var tr = dt.rows({ selected: true });

                    var example = dt.rows({ selected: true }).data().toArray();
                    var values = $.map(example, function (item) {
                        return item.task_id;
                    });

                    var ids = values.toString();

                    sendData.group_key = "taskid";
                    sendData.taskid = ids;

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

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

                    return false;
                }
            }
        ]

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

function yelp() {
    $(document).ready(function () {

        LoadDataTablesScripts(InitDatatable);

        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);

            if (_this.data('curr_on_date') && !_this.data('waiting')) {
                setEnableDatePicker(_this);
                return false;
            }

            ajaxPostSend($(this).attr('href'), $(this).data(), false, false);
            _this.closest('div.open').removeClass('open');
            return false;
        });

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

            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());

            if ($("#modalbox input[name='empty_confirm']").length !=0) {
                link.data('empty_confirm', 1);
            }

            link.trigger('click');

            return false;
        });

        // Group action for publish Date
        $(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();
                sendData.shedulepage = 1;

                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.addEventListener("DOMContentLoaded", yelp, false);

var removeTasks = function (obj) {
    $('#datatable-1').DataTable().row( $(obj).closest('tr') ).remove().draw();
};

function setEnableDatePicker(obj) {
    var isGroupAction = !obj.hasClass("main_ajax");
    var table = $("#datatable-1").DataTable();

    if( isGroupAction ) {
        obj = $("a.main_ajax[data-taskid][data-videoid='" +table.rows({ selected: true }).data().toArray()[0].video_id+ "']")
    }

    $('#modalbox').find('.modal-header-name span').text('{{ 'Schedule'|trans }}');

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

    if ( !isGroupAction || table.rows({ selected: true }).count() == 1 )
    {
        $('#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="text" id="video_on_date" class="form-control own_fields datepicker-field" data-date-format="dd-mm-yy" name="video_on_date" value="'+obj.data('publish_on')+'">\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>');

        $(".datepicker-inline").datepicker({
                language    : 'ru',
                dateFormat  : 'dd-mm-yy',  // actual format is dd-mm-yyyy don't change to -yy becouse server will parse date as yy-mm-dd when save
                defaultDate : $("input[name=video_on_date]").val(),
                firstDay    : 1,
                minDate     : new Date(),
                //altField    : "input#video_on_date",
                //altFormat   : "dd-mm-yy",
                currentText : '{{ 'Today'|trans }}',
                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( dateText );
                }
            }
        );

        // Put back dafault action of Today button click
        $.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();
            }
            this._notifyChange(inst);
            this._adjustDate(target);
        };

    } else {

        $('#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>');

        $(".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 }}',
                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() );
                }
            }
        );

        // 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")

    }

    $("input[name=video_on_date]")
        .on("change",function(){
            $('.datepicker-inline').datepicker("setDate", $(this).val() );
        })
        .on("keyup",function(e){
            e.preventDefault();
            e.stopPropagation();

            if( e.keyCode == 13 ){
                $("#apply_enable_date").click();
                return false;
            }

            $('.datepicker-inline').datepicker("setDate", $(this).val() );
        });

    // prevent submiting form on Enter press at text field
    $(window).keydown(function(event){
        if(event.keyCode == 13) {
            event.preventDefault();
            return false;
        }
    });

    // ?? 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 closeModalBox(){
    $("#modalbox").hide().removeClass();
    $(".datepicker-inline").datepicker( "destroy" );
    $('#modalbox').find('.modal-header-name span').empty();
    $('#modalbox').find('.devoops-modal-inner').empty();
    $('#modalbox').find('.devoops-modal-bottom').empty();
}

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');
}
