
        var  select2Opt = select2OptMS = select2OptPH = {minimumResultsForSearch: -1, dropdownAutoWidth: false, width: '100%'};
        var  select2OptMS = select2Opt, select2OptPH = select2Opt;
        select2OptMS.maximumSelectionSize = 4;
        select2OptPH.placeholder = '';

        var conf = {
            form: '#form_',
            lang : '{{ app.js_validator_language }}',
            showHelpOnFocus : true,
            validateHiddenInputs: true,
            ignore: ['.ignore'],
            modules: 'jsconf',
            errorClass: "myErrorClass",
            onSuccess: function () {
                $(this.form).get(0).submit();
                return false;
            },
            onError: function () {
                var _this = this;
                $(_this.form + " select").each(function(){
                    if ($(this).hasClass('error')) {
                        _this.highlight(this, _this.errorClass);
                    } else {
                        _this.unhighlight(this, _this.errorClass);
                    }
                });
                return false;
            },
            highlight: function (element, errorClass, validClass) {
                var elem = $(element);
                if (elem.hasClass("select2-offscreen")) {
                    $("#s2id_" + elem.attr("id") + " ul").addClass(errorClass);
                    $("#s2id_" + elem.attr("id") + " a").addClass(errorClass);
                } else {
                    elem.addClass(errorClass);
                }
            },
            unhighlight: function (element, errorClass, validClass) {
                var elem = $(element);
                if (elem.hasClass("select2-offscreen")) {
                    $("#s2id_" + elem.attr("id") + " ul").removeClass(errorClass);
                    $("#s2id_" + elem.attr("id") + " a").removeClass(errorClass);
                } else {
                    elem.removeClass(errorClass).removeAttr('style');
                }
            }
        };

        function DemoSelect2() {
                checkCatGenreList('#form_category_id', '#form_cat_genre_id');
                $('#form_category_id').select2(select2OptPH);
                $('#form_cat_genre_id').select2(select2OptMS);
                $('#form_genres').select2(select2OptMS);
                $('#form_protocol').select2(select2Opt);
                $('#form_volume_correction').select2(select2Opt);
                $('#form_rating_mpaa').select2(select2Opt);
                $('#form_age').select2(select2Opt);
        }

        function initFileUploader(){
            $('#fileupload').fileupload({
                url: 'video-club/edit-cover?id=' + ($('#form_cover_id').val() ? $('#form_cover_id').val() : 'new'),
                type: 'POST',
                autoUpload: true,
                multipart: true,
                acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
                maxFileSize: 1000000,
                maxNumberOfFiles: 1
            }).bind('fileuploaddone', function (e, data) {
                var response;
                if (data && data.jqXHR && data.jqXHR.status && data.jqXHR.status == 200 && data.jqXHR.responseJSON) {
                    response = data.jqXHR.responseJSON;
                } else {
                    JSErrorModalBox();
                    return false;
                }

                $(this).prev('div').children('img').attr('src', response.pic + '?' + $.random(100000)).css('max-width', '100%');
                var val = response.pic.split('/');
                val = val[val.length - 1];

                var imageName = val.split('.');
                if (imageName.length > 1) {
                    imageName.length -= 1;
                }

                $('#form_cover_id').val(imageName);
                $('#form_cover_big').val('');
                imageName = imageName.join('.');
                var postUrl = 'video-club/edit-cover?id=' + (typeof (imageName) != 'undefined' && imageName != '' ? imageName : 'new');
                $(this).fileupload('option', {url: postUrl});

                $("#cover_container a").data("cover_id", (imageName.search('new') != -1 ? val: imageName));
            });
            return true;
        }

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

                $.validate(conf);

                LoadSelect2Script(DemoSelect2);

                if (typeof (loadFileUploadScripts) != 'function' || !loadFileUploadScripts(initFileUploader)){
                    JSErrorModalBox({msg: "{{ 'Cannot load File Upload plugin'|trans }}"})
                }

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

                    if ($(conf.form).isValid({}, conf, true)) {
                        conf.onSuccess();
                    } else {
                        conf.onError();
                    }
                    return false;
                });

                $("#form_reset").on('click', function(e){
                    e.stopPropagation();
                    e.preventDefault();
                    $(this).closest('form').get(0).reset();
                    return false;
                });
                
                $(document).on('change', '#form_category_id', function(){
                   checkCatGenreList('#form_category_id', '#form_cat_genre_id');
                });
                
                $(document).on('change', '#form_protocol', function(e){
                   checkProtocol();
                });                
                
                $(document).on('change keyup', '#form_name, #form_year', function(e){
                    var _this = $('#form_name');
                    _this.next('div').removeClass('bg-danger').css('visibility', 'hidden').html('&nbsp;');
                    
                    if ($.trim(_this.val()) == '' && $.trim($('#form_o_name').val()) == '') {
                        $('#form_kinopoisk_id').removeAttr('readonly');
                    } else {
                        $('#form_kinopoisk_id').attr('readonly', 'readonly');
                    }
                    if ($.trim(_this.val()) == '' ) {
                        return;
                    }
                    
                   $.ajax({
                        url: 'video-club/check-name',
                        type: 'POST',
                        data: {name: _this.val(), year: $.trim($('#form_year').val()), 'id<>': $("#form_id").val()},
                        success: function (data) {
                            if (data.success) {
                                _this.next('div').append('<i class="txt-success fa fa-check"></i> ' + data.chk_rezult).css('visibility', 'visible');
                            } else if (data.error){
                                alert(data.error);
                            } else {
                                alert("{{ 'Some server error'|trans }}");
                            }
                        },
                        error: function (data) {
                            if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.error) != 'undefined') {
                                _this.next('div').append('<i class="txt-danger fa fa-ban"></i> ' + data.responseJSON.error).css('visibility', 'visible');
                            } else {
                                alert("{{ 'Some network error or access denied'|trans }}");
                            }
                        },
                        dataType: "json",
                        async: false
                    });
                });
                
                $(document).on('change keyup', '#form_o_name', function(e){
                    if ($.trim($(this).val()) == '' && $.trim($('#form_name').val()) == '') {
                        $('#form_kinopoisk_id').removeAttr('readonly');
                    } else {
                        $('#form_kinopoisk_id').attr('readonly', 'readonly');
                    }
                    checkAutocompliteButton('#form_o_name', '#form_kinopoisk_id');
                });
                
                $(document).on('change keyup', '#form_kinopoisk_id', function(e){
                    checkAutocompliteButton('#form_kinopoisk_id', '#form_o_name');
                });
                
                checkProtocol();
                
                $(document).on('click', '#update_rating_kinopoisk', function(){
                    $.ajax({
                        url: 'video-club/update-rating-kinopoisk',
                        type: 'POST',
                        data: {data: $("#form_o_name").val() || $("#form_name").val()},
                        success: function (data) {
                            if (data.success) {
                                $('#kinopoisk_url').attr('href', '');
                                $('#kinopoisk_url').html('');
                                for (var id in data.result){
                                    if (data.result.hasOwnProperty(id)){
                                        $("#form_"+id).val(data.result[id]);

                                        if (id == 'kinopoisk_url'){
                                            $('#kinopoisk_url').attr('href', data.result[id]);
                                            $('#kinopoisk_url').html(data.result[id]);
                                        }
                                    }
                                }
                            } else if (data.error){
                                alert(data.error);
                            } else {
                                alert("{{ 'Some server error'|trans }}");
                            }
                        },
                        error: function (data) {
                            if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.error) != 'undefined') {
                                alert(data.responseJSON.error);
                            } else {
                                alert("{{ 'Some network error or access denied'|trans }}");
                            }
                        },
                        dataType: "json",
                        async: false
                    });
                    
                });
                
                $(document).on('click', '#autocomplete_name, #autocomplete_id', function(){
                    if ($("#modalbox > div").css('display') != 'none') {
                        $("#modalbox > div").hide();
                    }    
                    $("#modalbox").show();
                    JSshowModalBox();
                    $.ajax({
                        url: 'video-club/get-kinopoisk-info-by-'+ $(this).attr('id').replace('autocomplete_', ''),
                        type: 'POST',
                        data: {data: $(this).closest('div').prev('div').find('input').val()},
                        success: function (data) {
                            if (typeof(conf) != 'undefined' && typeof(conf.form) != 'undefined' && typeof($.validate) == 'function') {
                                $.validate();
                                $(conf.form).get(0).reset();
                            }
                            $("#modalbox").hide();
                            $("body").removeClass("modal-open");
                            if (data.success) {
                                JSSuccessModalBox(data);
                                if (data.result.hasOwnProperty('cover_big')){
                                    $('#form_cover_id').next('img').attr('src', "video-club/get-image?url="+data.result['cover_big']);
                                    /*$('#form_cover_id').val('');*/
                                }

                                if (data.result.hasOwnProperty('age')){
                                    $('#form_age option[value="'+data.result.age+'"]').prop('selected', 'selected');
                                }

                                if (data.result.hasOwnProperty('rating_mpaa')){
                                    $('#form_rating_mpaa option[value="'+data.result.rating_mpaa+'"]').attr('selected', 'selected');
                                }

                                for (var id in data.result){
                                    if (data.result.hasOwnProperty(id)){

                                        $("#form_"+id).val(data.result[id]);

                                        if (id == 'kinopoisk_url'){
                                            $('#kinopoisk_url').attr('href', data.result[id]);
                                            $('#kinopoisk_url').html(data.result[id]);
                                        }
                                    }
                                }
                            } else if (data.error){
                                JSErrorModalBox(data);
                            } else {
                                JSErrorModalBox({'msg': "{{ 'Some server error'|trans }}"});
                            }
                        },
                        error: function (data) {
                            $("#modalbox").hide();
                            if (typeof(data.responseJSON) != 'undefined' && typeof(data.responseJSON.error) != 'undefined') {
                                JSErrorModalBox(data.responseJSON);
                            } else {
                                JSErrorModalBox({'msg': "{{ 'Some network error or access denied'|trans }}"});
                            }
                        },
                        dataType: "json",
                        async: false
                    });

                });

                $("#cover_container").on('click', 'a', function(e){
                    e.stopPropagation();
                    e.preventDefault();
                    JSshowModalBox();
                    if ($(this).data('cover_id')) {
                        ajaxPostSend($(this).attr('href'), {cover_id: $(this).data('cover_id')});
                    } else {
                        deleteCover();
                    }
                    return false;
                });
            });

        }

            document.addEventListener("DOMContentLoaded", yelp, false);
            
            var cat_genre_list = {
            {% for key, g_item in app['preparedCatGenre'] %}
                '{{ key }}' : [{% for g_in_item in g_item %}{'id': '{{ g_in_item['id'] }}', 'title':'{{ g_in_item['title'] }}'}{% if not loop.last %},{% endif %}{% endfor %}]{% if not loop.last %},{% endif %}
            {% endfor %}
            };

            var category_list = {
            {% for g_item in app['catGenres'] %}
                '{{ g_item['id'] }}' : '{{ g_item['category_alias'] }}'{% if not loop.last %},{% endif %}
            {% endfor %}
            };

            function checkCatGenreList(parent, child){
                var selAlias = category_list[$(parent).val()];
                var selChildData = $(child).val();
                $(child).empty();
                if (typeof(cat_genre_list[selAlias]) != 'undefined') {
                    $.each(cat_genre_list[selAlias], function(index, value){
                        $(child).append('<option value="'+value.id+'" '+($.inArray(value.id, selChildData) != -1? 'selected="selected"': '')+'>'+value.title+'</option>');    
                    });
                }
                $(child).select2(select2OptMS);
                return;
            }
            
            function checkProtocol(){
                var protocol = $("#form_protocol");
                if (protocol.val() != 'custom') {
                    protocol.closest('.form-group').next('div.form-group').hide();
                    $('#form_rtsp_url').attr('disabled', 'disabled');
                } else {
                    protocol.closest('.form-group').next('div.form-group').show();
                    $('#form_rtsp_url').removeAttr('disabled');
                }
            }
            
            function checkAutocompliteButton(master, slave){
                var buttonContainer = $(slave).parent('div').next();
                if ($.trim($(master).val()) != '') {
                    buttonContainer.find('button').attr('disabled', 'disabled').removeClass('btn-success');
                    buttonContainer.find('i').removeClass('txt-success').removeClass('fa-check').addClass('txt-danger').addClass('fa-ban');
                } else {
                    buttonContainer.find('button').removeAttr('disabled').addClass('btn-success');
                    buttonContainer.find('i').removeClass('txt-danger').removeClass('fa-ban').addClass('txt-success').addClass('fa-check');
                }
            }

            var deleteCover = function(data){
                $('#form_cover_id').val('');
                $('#form_cover_big').val('');
                $('#cover_container img').attr('src', '');
                JSSuccessModalBox(data);
            };

            var deleteCoverError = function(data){
                JSErrorModalBox(data);
            };

            var closeModalBox = function(){
                JScloseModalBox();
            };
