
var select2Opt = {minimumResultsForSearch: -1, dropdownAutoWidth: false, width: '100%'};

var conf = {
    lang : '{{ app.js_validator_language }}',
    form : '#modalbox form',
    showHelpOnFocus : true,
    validateHiddenInputs: true,
    scrollToTopOnError: false,
    validationRuleAttribute : 'data-validation',
    modules: 'jsconf',
    onkeyup: false,
    errorClass: "error",

    onError: function () {
        var _this = this;
        console.log( this );

        $(_this.form + " select").each(function(){

            if ($(this).hasClass(_this.errorClass)) {
                _this.highlight(this, _this.errorClass);
            } else {
                _this.unhighlight(this, _this.errorClass);
            }
        });
        return false;
    },

    highlight: function (element, errorClass, validClass) {
        if (!$(element).parent().children().find('.selection').children().hasClass(errorClass)) {
            $(element).parent().children().find('.selection').children().addClass(errorClass);
        }
    },
    unhighlight: function (element, errorClass, validClass) {
        $(element).parent().children().find('.selection').children().removeClass(errorClass);
    }
};

function InitSelect2() {
    $('#category_id').select2(select2Opt);
}

function InitDatatable() {
    $('#datatable-1').on('xhr.dt', function (e, settings, json) {
        if (typeof (json.data) == 'object') {
            for (var i in json.data) {
                var id = json.data[i].id;
                var movie_in_genre = parseInt(json.data[i].movie_in_genre, 10);
                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 }}/video-genres-list-json' class='main_ajax no_context_menu' data-id='" + id + "' id='edit_video_genres_" + id + "'>\n\
                                                            <span>{{ 'Edit'|trans }}</span>\n\
                                                        </a>\n\
                                                    </li>\n\
                                                    <li>\n\
                                                        <a class='main_ajax no_context_menu' " + (movie_in_genre ? "disabled='disabled'" : "") + " href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/remove-video-genres' data-genresid='" + id + "'>\n\
                                                            <span>{{ 'Delete'|trans }}</span>\n\
                                                        </a>\n\
                                                    </li>\n\
                                                </ul>\n\
                                            </div>";
                var title = json.data[i].title;

                json.data[i].title = "<a href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-genres-list-json' class='main_ajax no_context_menu' data-id='" + id + "' id='edit_video_genres_" + id + "'>" +escapeHtml( title )+ "</a>";
                json.data[i].localized_title = escapeHtml( json.data[i].localized_title );
                json.data[i].category = escapeHtml( json.data[i].category );
            }
        }
    }).dataTable({
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/video-genres-list-json"
        },
        "language": {
            "url": "{{ app.datatable_lang_file }}"
        },
        
        {% if attribute(app, 'dropdownAttribute') is defined %}
        {{ main_macro.get_datatable_column(app['dropdownAttribute']) }}
        {% endif %}
                
        "scrollCollapse": true,
        "bFilter": true,
        "bPaginate": true,
        "lengthChange": true,
        "bInfo": true,

        fixedHeader: {
            header: true,
            headerOffset: $('header.navbar').height()
        },

        "aoColumnDefs": [
            { className: "action-menu", "targets": [ -1 ]},
            { "sortable": false, "targets": [-1, 1, 2]},
            { "searchable": false, "targets": [-2, -1, 1, 2]}
        ]
    }).prev('.dataTables_processing').hide('');
}

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

        $.validate(conf);

        $(document).on('click', "a.main_ajax", function (e) {
            e.stopPropagation();
            e.preventDefault();
            if ($(this).attr('disabled') && $(this).attr('href').search('remove-video-genres') != -1) {
                JSErrorModalBox({msg: "{{ 'You can\'t delete genre with movies'|trans }}"});
            } else {
                ajaxPostSend($(this).attr('href'), $(this).data(), false);
            }
            $(this).closest('div.open').removeClass('open');
            return false;
        });

        $(document).on('click', '#add_video_genres', function (e) {
            e.stopPropagation();
            e.preventDefault();
            openModalBox($(this));
            return false
        });

        $(document).on('click', "#modalbox button[type='reset'], #modalbox, #modalbox a.close-link, #modalbox a.close-link *", function (e) {
            if (e.currentTarget != e.target) {
                return;
            }
            e.stopPropagation();
            e.preventDefault();
            closeModalBox();
            return false;
        });

        $(document).on('click submit', "#modalbox button[type='submit'], #modalbox form", function (e) {
            if (e.currentTarget != e.target) {
                return;
            }

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

            if ( $("#modalbox form").isValid({}, conf, true) && $.trim($("#modalbox input[name='title']").val()) ) {
                var sendData = {
                    id: $("#modalbox input[name='id']").val(),
                    title: $("#modalbox input[name='title']").val(),
                    category_alias: $("#category_id").val()
                };
                ajaxPostSend($("#modalbox form").attr('action'), sendData, false);
            } else {
                conf.onError();
            }
            return false;
        });


        $(document).on('change', '#category_id', function () {
            $(this).validate(function(valid, elem) {
                if (valid) {
                    conf.unhighlight(elem, conf.errorClass);
                } else {
                    conf.highlight(elem, conf.errorClass);
                }
            } );
        });

        LoadDataTablesScripts(InitDatatable);
        // useless - no select at this point:
        //LoadSelect2Script(InitSelect2);

    });
}

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

function closeModalBox(){
    $("#modalbox").hide();
    $('#category_id').select2("destroy");
    $('#modalbox').find('.modal-header-name span').empty();
    $('#modalbox').find('.devoops-modal-inner').empty();
}

function openModalBox(obj){
    $('#modalbox').find('.modal-header-name span').text( (obj.data instanceof Array) ? '{{ 'Edit genre'|trans }}' : '{{ 'Add genre'|trans }}' );

    if ($('#modalbox').find('.devoops-modal-inner').find('input').length == 0) {
        $('#modalbox').find('.devoops-modal-inner').html('\n\
            <form class="form-horizontal" role="form">\n\
                <div class="box-content">\n\
                    <div class="form-group">\n\
                        <label class="col-sm-3 control-label col-sm-offset-1">{{ 'Genre'|trans }}<span class="icon-required">*</span></label>\n\
                        <div class="col-xs-10 col-sm-8">\n\
                            <span class="col-xs-8 col-sm-8">\n\
                                <input type="hidden" name="id">\n\
                                <input type="text" class="own_fields form-control " name="title"  data-validation="required"  id="genre_title">\n\
                                <div class="name-check"></div>\n\
                            </span>\n\
                        </div>\n\
                    </div>\n\
                    <div class="form-group">\n\
                        <label class="col-sm-3 control-label col-sm-offset-1">{{ 'Category'|trans }}<span class="icon-required">*</span></label>\n\
                        <div class="col-xs-10 col-sm-8">\n\
                            <span class="col-xs-8 col-sm-8">\n\
                                <select name="category_alias" class="populate placeholder"  data-validation="required"  id="category_id">\n\
                                {% if attribute(app, 'allCategories') is defined %}
                                    <option>&nbsp;</option>\n\
                                    {% for cat_item in app.allCategories %}
                                    <option value="{{ cat_item.category_alias }}">{{ cat_item.category_name }}</option>\n\
                                    {% endfor %}
                                {% endif %}
                                </select>\n\
                            </span>\n\
                        </div>\n\
                    </div>\n\
                </div>\n\
            </form>');
        $('#modalbox').find('.devoops-modal-bottom').html('\
            <div class="col-xs-12">\n\
                <button type="submit" class="btn btn-success col-sm-2 pull-right">{{ 'Save'|trans }}</button>\n\
                <button type="reset"  class="btn btn-default col-sm-2 pull-right" >{{ 'Cancel'|trans }}</button>\n\
            </div>');

        $('#category_id').select2(select2Opt);
        $.validate(conf);
    }
    /* Don't use this code to empty select2
    $('#category_id').select2("val", "");
    becouse of
    'onchange' #category_id
    reinitialize select2 instead
    */

    if (obj.data instanceof Array) {
        $('#modalbox').find('.devoops-modal-inner input[name="id"]').val(obj.data[0].id);
        $('#modalbox').find('.devoops-modal-inner input[name="title"]').val(obj.data[0].title);
        $('#category_id option[value="' + obj.data[0].category_alias + '"]').prop('selected', 'selected');
        $("#category_id").trigger("change");
    } else {
        $('#modalbox').find('.devoops-modal-inner *[name]').val('');
        $('#category_id option').prop('selected', false).removeAttr('selected');
        $('#category_id').select2(select2Opt);
    }


    $('#modalbox .name-check').html('').hide();
    $('#modalbox button[type="submit"]').removeAttr("disabled");
    $('#modalbox form').attr('action', "{{app.request_context.baseUrl}}/{{app.controller_alias}}/save-video-genres");
    $("#modalbox").show();
    $(obj).closest('div.open').removeClass('open');
}
