/*
 this component has templates in .twig file
*/

var sendCounter = 0;

var pendingList = [];

var conf = {
    form: '#form_',
    lang : '{{ app.js_validator_language }}',
    showHelpOnFocus : true,
    validateHiddenInputs: true,
    validateOnBlur: true,
    ignore: ['.ignore'],
    modules: 'jsconf, date, security',
    errorClass: "error",
    onSuccess: function () {
        if (this.form == '#form_') {
            if (typeof (pendingList) != "undefined" && pendingList instanceof Array && pendingList.length != 0){
                if (!$("#modalbox").is(':visible')) {
                    $('#modalbox').find('.modal-header-name span').text("{{ 'Uploading progress'|trans }}");
                    $("#modalbox .devoops-modal-inner").empty();
                    $("#modalbox").show();
                }
                pendingList.forEach(function (data) {
                    var name = '';
                    if (typeof(data.files) != "undefined" && data.files.length) {
                        name = "{{ 'Image'|trans }} " + data.files[0].name;
                    }
                    var progress_id = 'qq-progress-bar-' + data.formData.file_num;
                    data.progress_id = progress_id;
                    $("#modalbox .devoops-modal-inner").append('\n\
                    <span class="col-sm-10 col-sm-offset-1" style="text-align: center;">'+name+'</span>\n\
                    <div class="qq-progress-bar-container-selector">\n\
                        <div id="' + progress_id + '" class="tu-progress-bar ui-progressbar ui-widget ui-widget-content ui-corner-all" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" style="width: 90%; margin-left: 5%;">\n\
                            <div class="qq-progress-bar-selector ui-progressbar-value ui-widget-header ui-corner-left" style="width: 0%;"></div>\n\
                        </div>\n\
                    </div>');
                    data.submit();
                });
            }

            var submittedFileTimer = window.setInterval(function(){
                if ((typeof (pendingList) != "undefined" && pendingList instanceof Array && pendingList.length == 0) || (typeof (window.submitTry) != "undefined" && window.submitTry >= 300)){
                    window.clearInterval(submittedFileTimer);
                    if (typeof (window.submitTry) != "undefined" && window.submitTry >= 300) {
                        JSErrorModalBox({msg: "{{ 'One or more images not be loaded'|trans }}"});
                    }
                    $('#form_').get(0).submit();
                } else {
                    window.submitTry = typeof (window.submitTry) != "undefined" ? window.submitTry++: 0;
                }
            }, 100);
        }
        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) {
        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);
    }
};

var select2Opt = {minimumResultsForSearch: -1, dropdownAutoWidth: false, width: '100%', allowDuplicates: true};
var select2OptMS = {maximumSelectionSize: 4, maximumSelectionLength: 4},
    select2OptPH = $.extend({
                                placeholder: {
                                    id: "-1",
                                    text: "",
                                    selected: 'selected'
                                }
                            }, select2Opt);
$.extend(select2OptMS, select2Opt);
select2OptMS.minimumResultsForSearch = 1;

var s2Opts;

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

function matchStart (term, text) {
    $("#fileLangCloneList").find('input').val(term);
    return text.toUpperCase().indexOf(term.toUpperCase()) != -1;
}

function changeLangBlockHeight(){
    if ($("#fileLangCloneList").height() >= $('#file_languages').next().height()) {
        $("#fileLangCloneList").parent().css({paddingTop: $("#fileLangCloneList").height() - $('#file_languages').next().height() + 'px'});
    } else {
        $("#fileLangCloneList").find('.select2-selection').css({minHeight: $('#file_languages').next().height() + 'px'});
        $("#fileLangCloneList").parent().css({paddingTop: 0});
    }
}

function setFileLanguagesSelect(){
    var file_languages  = $('#file_languages').select2(s2Opts);

    if ($('#fileLangCloneList').length) {
        $('#fileLangCloneList').remove();
    }
    file_languages.parent().css({position: 'relative', overflow: 'hidden'});
    var fileLangList = file_languages.next();
    var cloneList = fileLangList.clone(true, true);
    cloneList.insertAfter(fileLangList);

    cloneList.attr('id', 'fileLangCloneList').css({width: '93%', top: 0, left: 10, position: 'absolute'});
    /*file_languages.next().css({visibility: 'hidden'});*/
    cloneList.find('input').css({minWidth: '10px'});


    cloneList.on('select2:selecting', function(e){
        e.stopPropagation();
        e.preventDefault();
       return false;
    });
    cloneList.on('select2:opening', function(e){
        e.stopPropagation();
        e.preventDefault();
        return false;
    });

    fileLangList.find('li, li *').on('input keyup change', function(){
        var oInput = fileLangList.find('input');
        var inputWidth = cloneList.find('input').outerWidth();
        var calcWidth = oInput.val().length * 10;
        if (inputWidth < calcWidth) {
            inputWidth = calcWidth;
        }
        cloneList.find('input').css('width', inputWidth).val(oInput.val());
    });

    function getInputWidth(){
        var containerWidth = cloneList.find('ul').innerWidth();
        var rowWidth = 0;
        cloneList.find('ul').children().each(function(){
            if (!$(this).hasClass('select2-search--inline')) {
                var oWidth = $(this).outerWidth() + 10;
                rowWidth += oWidth;
                if (rowWidth >= containerWidth) {
                    rowWidth = oWidth;
                }
            }
        });
        var inputWith = containerWidth - rowWidth - 20;
        return inputWith < 20 ?  'auto': inputWith;
    }

    file_languages.on('select2:selecting', function(e){
        var lastTimestamp = $("#fileLangCloneList").data('last-timestamp');
        var lastGuid = $("#fileLangCloneList").data('last-guid');
        if (lastTimestamp != e.timeStamp){
            var liTmpl = $('<li class="select2-selection__choice" title=""><span role="presentation" class="select2-selection__choice__remove">×</span></li>').insertBefore($("#fileLangCloneList").find('li.select2-search'));
            var val = $(this).data().select2.results.getHighlightedResults().attr('id').split('-').slice(-1)[0];
            var textLabel = $(this).data().select2.results.getHighlightedResults().text();
            liTmpl.attr('title', textLabel);
            liTmpl.find('span').after(textLabel);
            liTmpl.data('val', val);
        }
        $("#fileLangCloneList").data('last-timestamp', e.timeStamp);
        $("#fileLangCloneList").data('last-guid', e.handleObj.guid);
    });

    file_languages.on('select2:select', function(e){
        changeLangBlockHeight();
        fileLangList.find('input').val('');
        cloneList.find('input').css({width: getInputWidth()}).val('');
    });

    $("#file_languages, #fileLangCloneList").on('select2:closing', function(e){
        conf.form = '#' + $("#modalbox form").attr('id');
        if ($(conf.form).isValid({}, conf, true)) {
            getMediaInfo();
        } else {
            conf.onError();
        }
        fileLangList.find('input').val('');
        cloneList.find('input').css({width: getInputWidth()}).val('');
        changeLangBlockHeight();
    });

    $("#fileLangCloneList ul").on('mouseup mousedown select2:selecting select2:opening keyup keydown input', 'li, li *', function(e){
        e.stopPropagation();
        e.preventDefault();
        return false;
    });

    $("#fileLangCloneList").on('click', 'li.select2-selection__choice', function(e){
        e.stopPropagation();
        e.preventDefault();
        var curVal = $(this).data('val');
        $(this).remove();
        var langData = [];
        $("#fileLangCloneList li").each(function(i){
            langData.push($(this).data('val'));
        });
        $('#file_languages').val(langData).trigger('change.select2');
        changeLangBlockHeight();
        $('#file_languages').data().select2.trigger('close');
        return false;
    });

}

function initFileUploader(){
    $('#cover_container, div[id^="video_episodes_"]').fileupload({
        url: '{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/edit-cover',
        type: 'POST',
        autoUpload: false,
        multipart: true,
        multiple: true,
        singleFileUploads: true,
        limitMultiFileUploads: 10,
        acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
        maxFileSize: 1000000,
        maxNumberOfFiles: 10
    }).bind('fileuploadadd', function (e, data) {
        if (e.currentTarget.id.search('video_episodes_') == -1){
            $(this).fileupload(
                    'option',
                    'previewMaxWidth',
                    '484px'
            );
            $(this).fileupload(
                    'option',
                    'previewMaxHeight',
                    '363px'
            );
        } else {
            $(this).fileupload(
                    'option',
                    'previewMaxWidth',
                    '101px'
            );
            $(this).fileupload(
                    'option',
                    'previewMaxHeight',
                    '68px'
            );
        }
    }).bind('fileuploadadded', function (e, data) {
        var container, img, params = {}, currentFile, id;
        container = e.currentTarget;
        id = container.id.search('video_episodes_') == -1 ? 0: parseInt(container.id.replace(/[^\d]*/ig, ''), 10);
        currentFile = data.files[0];
        img = $(container).next('img');

        if (img.attr('src') || $(container).attr('qq-file-id')) {
            img = false;
            $("#cover_container, div[id^='video_episodes_']").each(function(){
                if (!$(this).next('img').attr('src') && !$(this).attr('qq-file-id') ) {
                    id = this.id.search('video_episodes_') == -1 ? 0: parseInt(this.id.replace(/[^\d]*/ig, ''), 10);
                    $(this).attr('qq-file-id', id);
                    params = {
                        id: $(this).data('id'),
                        file_num: ''+$(this).data('file_num'),
                        video_id: ($("#form_id").val() ? $("#form_id").val() : 'new')
                    };
                    img = $(this).next('img');
                    return false;
                }
            });
            if (img === false) {
                return false;
            }
        } else {
            $(container).attr('qq-file-id', id);
            params = {
                id: $(container).data('id'),
                file_num: ''+$(container).data('file_num'),
                video_id: ($("#form_id").val() ? $("#form_id").val() : 'new')
            };
        }

        if (typeof(data.formData) == 'undefined') {
            data.formData = {};
        }

        data.formData = params;

        img.attr('src', currentFile.preview.toDataURL(currentFile.type));
        if (!img.is(':visible')) {
            img.show();
        }
        pendingList.push(data);
    }).bind('fileuploadalways', function (e, data) {
        if (typeof(data.progressWorkTimer) != "undefined") {
            window.clearInterval(data.progressWorkTimer);
        }

        var name = '';
        if (typeof(data.files) != "undefined" && data.files.length) {
            name = "{{ 'Image'|trans }} " + data.files[0].name;
        }

        var progress_id = ( typeof(data.progress_id) != "undefined" ? data.progress_id: 'qq-progress-bar-' + data.formData.file_num);

        $('#' + progress_id).attr('aria-valuenow', 100);
        $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(name + ' ' + "{{ 'saving'|trans }}");
        $('#' + progress_id + " > div").css("width", "100%");
        var file_num = '' + data.formData.file_num;
        if (typeof (pendingList) != "undefined" && pendingList instanceof Array && pendingList.length && file_num) {
            $.each(pendingList, function (i) {
                if (file_num && this.formData && this.formData.file_num && this.formData.file_num == file_num) {
                    pendingList.splice(i,1);
                }
            });
        }
    }).bind('fileuploadprogress', function (e, data) {
        var name = '';
        if (typeof(data.files) != "undefined" && data.files.length) {
            name = "{{ 'Image'|trans }} " + data.files[0].name;
        }
        var value_now = Math.round(data.loaded / data.total * 100);
        var progress = '"' + name + '" '+"{{ 'uploading'|trans }}"+'...  ' + value_now + '%';
        var progress_id = ( typeof(data.progress_id) != "undefined" ? data.progress_id: 'qq-progress-bar-' + data.formData.file_num);
        if (data.loaded < data.total) {
            $('#' + progress_id).attr('aria-valuenow', value_now);
            $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(progress);
            $('#' + progress_id + " > div").css("width", value_now + "%");
        } else {
            $('#' + progress_id).attr('aria-valuenow', 100);
            $('#' + progress_id).closest('div.qq-progress-bar-container-selector').prev('span').html(name + ' ' + "{{ 'saving'|trans }}");
            $('#' + progress_id + " > div").css("width", "100%");
        }
    }).bind('fileuploaddone', function (e, data) {
        var result = data._response.result || false;

        if (result && result.success && result.upload_id) {
            if (result.file_num == 0) {
                $("#form_cover_id").val(result.upload_id);
            }
        } else {
            return false;
        }
        return true;
    });
    return true;
}

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

        $.fn.select2.amd.require([
            "select2/core",
            "select2/utils",
            "select2/compat/matcher"
        ], function (Select2, Utils, oldMatcher) {
            s2Opts = $.extend({}, select2OptMS, {matcher: oldMatcher(matchStart)});
        });

        // Add custom validation rule
        var customRuleObj = {
            name : 'compare_number',
            errorMessage : "",
            errorMessageKey: 'badCompareNumber'
        };

        customRuleObj.validatorFunction = function(value, el, config, language, form) {
            var compElem = $(el).data('validation-compare-element');
            var compOperation = $(el).data('validation-compare-operation') ? $(el).data('validation-compare-operation') : "<=";
            var compRegExpStr = $(el).data('validation-regexp');
            var compElemValidationOptional = $(compElem).data('validation-optional') || false;

            if (compRegExpStr) {
                var compRegExp = new RegExp(compRegExpStr, 'ig');
                if (!compRegExp.test($(el).val())){
                    this.errorMessage = language.badCustomVal;
                    return false;
                }
            }

            if (compElem && !$(compElem).is(":disabled")) {
                if (!$(compElem).val() && compElemValidationOptional) {
                    return true;
                }
                var val = parseFloat($(el).val());
                var compVal = parseFloat($(compElem).val());
                if ((compOperation == '<=' && !(val <= compVal)) || (compOperation == '>=' && !(val >= compVal))) {
                    this.errorMessage = "{{ 'End date can not be less than the start date'|trans }}";
                    return false;
                }
            }

            return true;
        };

        $.formUtils.addValidator(customRuleObj);

        $.validate(conf);

        LoadSelect2Script(DemoSelect2);

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

        //$('[data-toggle="tooltip"]').tooltip();
        $('.form-group .i-hint').tooltip({
            animation: true,
            placement: "right"
        });

        $("#files_container").on('click', '.box-header input, .box-header button, .mod_input i', function (e) {
            e.stopPropagation();
            e.preventDefault();
        });

        $("#files_container").on('blur keydown', 'input[name="season_original_name"], input[name="season_name"], input[name="series_original_name"], input[name="series_name"]', function(e){
            if ((e.type == 'blur' || e.type == 'focusout' || (e.type == 'keydown' && e.keyCode == 13)) && !$(this).data('is_sended')){
                e.stopPropagation();
                e.preventDefault();
                var params = {
                    id: $(this).closest("div[id*='season']").attr('id'),
                    field: $(this).attr('name'),
                    value: $(this).val(),
                    event: e.type
                };

                ajaxPostSend('{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/save-season-series-names', params, false, false);
                $(this).data('is_sended', 1);
                return;
            }
            if ($(this).data('is_sended') && e.type && e.type != 'keydown') {
                $(this).removeData('is_sended');
            }
        });

        $("#files_container").on('click', 'button[data-add-files]', function (e) {
            $("#modalbox").hide();
            $("#modalbox").data('complete', 1);
            $('#modalbox').find('.modal-header-name span').text("{{ 'Add file'|trans }}");
            $('#modalbox').find('.devoops-modal-inner').html($("#modal_save_form_body").text());
            $('#modalbox').find('.devoops-modal-bottom').html($("#modal_save_form_buttons").text());

            $("#file_id").remove();
            $("#file_name").remove();
            $("#video_id").val($("#files_container").data('video_id'));

            var seasonContainer = $(this).closest('div[id^="season_"]');
            if (seasonContainer.length) {
                $("#season_id").val(seasonContainer.data('seasonid'));
            } else {
                $("#season_id").remove();
            }

            var seriesContainer = $(this).closest('div[id^="s_season_"]');
            if (seriesContainer.length) {
                $("#series_id").val(seriesContainer.data('seriesid'));
            } else {
                $("#series_id").remove();
            }

            $("#file_protocol").prop({
                'readonly': 'readonly',
                'disabled': 'disabled'
            }).find('option[value="custom"]').prop({'selected': 'selected'});

            $('#file_type').select2(select2Opt);
            $('#file_quality').select2(select2Opt);
            setFileLanguagesSelect();
            $('#file_volume_level option[value="0"]').prop('selected', true);
            $('#file_volume_level').select2(select2Opt);
            $('#file_protocol').select2(select2Opt);
            $('#file_accessed').select2(select2Opt);
            $('#file_tmp_link_type').select2(select2OptPH);

            if ($(this).data('old-url')) {
                $("#video_url").val($(this).data('old-url')).after('<input type="hidden" class="own_fields" name="clean_old_url" value="1">');
                getMediaInfo();
            }

            $('#modalbox').show();
            if (!$(this).closest('a.collapse-link').next('.box-content').is(':visible')) {
                $(this).closest('a.collapse-link').trigger('click');
            }
        });

        $("#files_container").on('click', 'button[data-add-series]', function (e) {
            var container = $(this).closest('div[id^="season_"]');
            if (container.length) {
                var sendData = {
                    season_id: container.data('seasonid'),
                    series_number: container.find("span[data-series-count]").data("series-count")
                };
                ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/add-video-season-series", sendData, false);
            }
        });

        $("#files_container").on('click', 'button[data-delete-season]', function (e) {
            var container = $(this).closest('div[id^="season_"]');
            if (container.length) {
                var sendData = {
                    season_id: container.data('seasonid')
                };
                ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/delete-video-season", sendData, false, false);
            }
        });

        $("#files_container").on('click', 'button[data-delete-episode]', function (e) {
            var sendData = {};
            var container = $(this).closest('div[id^="s_season_"]');
            if (container.length) {
                var sendData = {
                    series_id: container.data('seriesid')
                };
                ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/delete-video-season-series", sendData, false, false);
            }
        });

        $("#files_container").on('click', "a.collapse-link", function(e){
            if ($(this).parent('div[id^="s_season_"]').length == 0 && $(this).next('div.box-content').is(':visible')) {
                $(this).next('div').find('.box-content:visible').prev('a.collapse-link').trigger('click');
            }
        });

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

            var seasonNumbers = new Array(), j;//.find("span[data-season-number]").data("season-number");

            $("#files_container").find('div[id^="season_"]').each(function(){
                seasonNumbers.push(parseInt($(this).find("span[data-season-number]").data("season-number"), 10));
                if ($(this).children('.box-content').is(':visible')){
                    $(this).children('a.collapse-link').trigger('click');
                }
            });

            var sendData = {
                video_id: $("#files_container").data('video_id'),
                season_number: seasonNumbers[seasonNumbers.length - 1] + 1
            };

            for(var i in seasonNumbers){
                j = parseInt(i, 10) +1;
                if (typeof(seasonNumbers[j]) != 'undefined' && seasonNumbers[i] + 1 != seasonNumbers[j]) {
                    sendData.season_number = seasonNumbers[i] + 1;
                    break;
                }
            }

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

        $("#season_button_container").on('click', '#add_season_structure', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $("#modalbox .modal-header-name span").empty().text("{{ 'Add seasons and episodes'|trans }}");
            $("#modalbox .devoops-modal-inner").empty();
            $($("#season_counter_template").html()).appendTo("#modalbox .devoops-modal-inner");

            $("#modalbox .devoops-modal-bottom").empty().append($("#modal_save_form_buttons").html());

            $('#season_counter').select2(select2Opt);
            $('<hr>').insertAfter($("#season_counter").closest('.form-group'));
            $("#season_counter").closest('.form-group').next('hr').css({minWidth: "100%", clear: "both", marginTop: "40px", marginBottom: "40px"});

            var selectBox = $($("#series_counter_template").html()).insertAfter($("#season_counter").closest('.form-group').next('hr'));
            selectBox.find('select').attr({name: 'season_structure[1]', id: 'series_counter_0'});
            selectBox.find('label').text(selectBox.find('label').text() + 1);
            $('#series_counter_0').select2(select2Opt);

            $("#modalbox").data('complete', 1).show();
        });

        $("#modalbox").on('change', "#season_counter", function(){
            if ($("#season_counter").closest('.form-group').next('hr').length == 0) {
                $('<hr>').insertAfter($("#season_counter").closest('.form-group'));
                $("#season_counter").closest('.form-group').next('hr').css({minWidth: "100%", clear: "both", marginTop: "65px"});
            }

            var currCount = parseInt($(this).val(), 10);
            var selectBoxes = $("#modalbox select[id^='series_counter_']");
            var selectBox;

            while(selectBoxes.length != currCount) {
                if (selectBoxes.length > currCount) {
                    $(selectBoxes.get(selectBoxes.length - 1)).closest('.form-group').remove();
                } else {
                    if (selectBoxes.length == 0) {
                        selectBox = $($("#series_counter_template").html()).insertAfter($("#season_counter").closest('.form-group').next('hr'));
                    } else {
                        selectBox = $($("#series_counter_template").html()).insertAfter(selectBoxes.get(selectBoxes.length - 1).closest('.form-group'));
                    }
                    selectBox.find('select').attr({name: 'season_structure[' + (selectBoxes.length + 1) + ']', id: 'series_counter_' + selectBoxes.length});
                    selectBox.find('label').text(selectBox.find('label').text() + (selectBoxes.length + 1));
                    $('#series_counter_' + selectBoxes.length).select2(select2Opt);
                }
                selectBoxes = $("#modalbox select[id^='series_counter_']");
            }

        });

        $("#modalbox").on("click", "button[type='submit']", function (e) {
            e.stopPropagation();
            e.preventDefault();

            conf.form = '#' + $("#modalbox form").attr('id');

            checkProtocol();
            checkFileType();

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

            var sendData = {};
            $("#modalbox form").find("input.own_fields, select.own_fields").filter(':not(:disabled)[id!="file_languages"]').each(function () {
                var _this = $(this);
                sendData[_this.attr('name')] = _this.val();
            });

            if ($("#modalbox form #file_languages").length) {
                sendData['languages'] = [];
                $('#fileLangCloneList li').each(function () {
                    sendData['languages'].push($(this).data('val'));
                });
            }

            ajaxPostSend($("#modalbox form").attr('action'), sendData, false);
            JScloseModalBox();
        });

        $("#modalbox").on("click", "button[type='reset']", function (e) {
            e.stopPropagation();
            e.preventDefault();

            var dataTable = ($("#season_id").length != 0 && $("#series_id").length != 0) ? 'f_season_' + $("#season_id").val() + '_series_' + $("#series_id").val() + '_filedata' : "filedata";
            if ($("#" + dataTable).length != 0) {
                dataTableUpdate({datatable: dataTable});
            }

            $.validate();
            $("#modalbox form").get(0).reset();
            /*$("#modalbox form").find("select.own_fields").each(function () {
                $(this).select2({minimumResultsForSearch: -1});
            });*/
            JScloseModalBox();
        });

        $("#files_container").on('click', 'a.main_ajax:not([disabled])', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $(this).closest("div.open").removeClass('open');

            var sendData = $(this).data();
            if ($(this).closest('tr').length && $(this).closest('tr').attr('id')) {
                sendData['RowOrder'] = $(this).closest('tr').attr('id');
            }
            ajaxPostSend($(this).attr('href'), sendData, false, false);
        });

        $("table[id*='filedata']").on("click", "a[href*='remove-video']", function (e) {
            e.stopPropagation();
            e.preventDefault();
            JScloseModalBox();
            $('#modalbox').find('.modal-header-name span').text("{{ 'Delete file'|trans }}");
            var id = $(this).data('id');
            if (id) {
                $('#modalbox').find('.devoops-modal-inner').html("\n\
                <form class='form-horizontal' role='form' action=''>\n\
                    <input type='hidden' class='own_fields form-control' name='id' value='' readonly='readonly'>\n\
                    <span class='col-xs-12 col-sm-12'>\n\
                        <span class='text-danger text-center'>\n\
                        {{ 'Do you really wont delete this record?'|trans }}\n\
                        </span>\n\
                    </span>\n\
                </form>\n\
                ");
                $('#modalbox').find('.devoops-modal-inner form').attr('action', $(this).attr('href'));
                $('#modalbox').find('.devoops-modal-inner form input').val($(this).data('id'));
                $('#modalbox').find('.devoops-modal-bottom').html($("#modal_save_form_buttons").text());
            } else {
                JSErrorModalBox({msg: "{{ 'This record cannot be deleted'|trans }}"});
            }
        });

        $(document).on("click", ".clear_video_episodes, #delete_cover", function (e) {
            e.stopPropagation();
            e.preventDefault();
            var img, container;
            if ($(this).hasClass('clear_video_episodes')) {
                img = $(this).prev('img');
                container = $(this).closest('li').find("div[id^='video_episodes_']").attr('id');
            } else {
                img = $("#cover_container").next('img');
                container = "cover_container";
            }
            img.hide(100, function () {
                img.attr('src', '');
            });
            img.css('display', 'inline');

            var id = $('#' + container).attr('qq-file-id');
            if (typeof(id) != 'undefined') {
                var file_num = ''+$('#' + container).data('file_num');
                if (typeof (pendingList) != "undefined" && pendingList instanceof Array && pendingList.length && file_num) {
                    $.each(pendingList, function (i) {
                        if (file_num && this.formData && this.formData.file_num && this.formData.file_num == file_num) {
                            this.abort();
                            pendingList.splice(i,1);
                        }
                    });
                }
            } else if($("#form_id").val()){
                ajaxPostSend('{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/delete-cover', {id: $("#" + container).data('id'), container: container}, false);
            }
            $('#' + container).removeAttr('qq-file-id');
            $(this).hide(50, function(){
                var _this = this;
                setTimeout(function(){
                    $(_this).removeAttr('style');
                }, 1000);
            });
        });

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

            conf.form = '#form_';

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

        $("#form_reset").on('click', function (e) {
            e.stopPropagation();
            e.preventDefault();
            $.validate();
            $(this).closest('form').get(0).reset();
            return false;
        });

        $(document).on('change', '#form_category_id', function () {
            checkCatGenreList('#form_category_id', '#form_cat_genre_id');
            $('#form_category_id, #form_cat_genre_id').validate(function(valid, elem) {
                if (valid) {
                    conf.unhighlight(elem, 'error');
                } else {
                    conf.highlight(elem, 'error');
                }
            });
        });

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

        $("#modalbox").on('change', '#file_protocol', function (e) {
            checkProtocol();
        });

        $("#modalbox").on('change', '#file_type', function (e) {
            checkFileType();
        });

        $(document).on('change keyup', '#form_name, #form_year', function (e) {
            var _this = $('#form_name');
            _this.next('div').removeClass('bg-danger').html('&nbsp;').hide();

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

            ajaxPostSend('{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/check-name', {name: _this.val(), year: $.trim($('#form_year').val()), 'id<>': $("#form_id").val()}, false, 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();

        checkFileType();

        $(document).on('click', '#update_rating_kinopoisk', function () {
            $.ajax({
                url: '{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/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
            });

        });

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

            var sendData = {
                provider: $("[id^='form_autocomplete_provider']").filter(':checked').val() || false
            };

            var searchBy;

            if (($('#form_o_name').val() && $('#form_o_name').val() != $('#form_o_name').data('oldvalue'))) {
                $('#form_o_name').data('oldvalue', $('#form_o_name').val());
                sendData.data = $('#form_o_name').val();
                searchBy = 'name';
            } else {
                sendData.data = ($('#form_kinopoisk_id').val() ? $('#form_kinopoisk_id').val() : $('#form_o_name').val());
                searchBy = ($('#form_kinopoisk_id').val() ? 'id' : 'name');
            }

            if (!sendData.provider || sendData.provider === ''){
                JSErrorModalBox({'msg': "{{ 'First, select the search service'|trans }}"});
            } else if (!sendData.data || sendData.data === '') {
                JSErrorModalBox({'msg': "{{ 'First enter the name or the movie id'|trans }}"});
            } else {
                if ($("#modalbox > div").css('display') != 'none') {
                    $("#modalbox > div").hide();
                }
                $("#modalbox").show();
                JSshowModalBox();
                ajaxPostSend('{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-kinopoisk-info-by-' + searchBy, sendData, false, false, true);
            }
        });

        checkVideoType();
        $(document).on("change", "#form_is_series", function () {
            checkVideoType();
        });

        $("#season_button_container").on("click", "#update_season", function (e) {
            e.stopPropagation();
            e.preventDefault();
            checkVideoType();
        });

        $(document).on("show", "div[id^='s_season_'] .box-content", function(e){
            /*var boxContent = $(this).closest('.box').children('.box-content');*/
            if (e && e.type && e.type == "show") {
                $.queue(this, "fx", function() {
                    var dataId = $(this).closest('.box').data();
                    if (!$("#" + dataId['table-id']).children('tbody').children('tr').length) {
                        fillFilesData(dataId['self-id'], dataId['table-id']);
                    }
                    /*$(this).find('table').DataTable().draw();*/
                    $.dequeue( this );
                });
                /*$(this).find('table').DataTable().ajax.reload();*/
            }
        });

        $('.mod_input').on('click', 'i.fa-pencil', function(e){
            $(this).prev('input').focus();
        });

        $("#files_container").on('blur', 'input', function(e){
            $(this).selectRange(0);
        });

        $("#modalbox").on('blur keypress', '#video_url', function(e){
            if (e && e.type && (e.type == "blur" || e.type == 'focusout' || (e.type == "keypress" && e.keyCode && e.keyCode == 13))) {

                conf.form = '#' + $("#modalbox form").attr('id');

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

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

            var fieldData = {};

            $("#media_info span").each(function(){
                if ($(this).data('info-key')) {
                    fieldData[$(this).data('info-key')] = $(this).data('info-val');
                    /*var fieldId = "#file_" + $(this).data('info-key');
                    if ($(fieldId).length !=0 ) {
                        var fieldVal = $(this).data('info-val');
                        if ($(fieldId).get(0).tagName.toUpperCase() == 'SELECT') {
                            $(fieldId).find('option').prop('selected', false).removeAttr('selected');
                            $.each(fieldVal.split(','), function(){
                                $(fieldId).find("option[value='"+this+"']").prop('selected', 'selected');
                            });
                            $(fieldId).select2(select2OptMS);
                        } else {
                            $(fieldId).val(fieldVal);
                        }
                    }*/
                }
            });

            if (fieldData.languages) {
                fieldData.languages = fieldData.languages.split(',');
            }

            fillModalBoxFilesData({data: fieldData}, true);
        });

        $('i[data-toggle="tooltip"]').tooltip();

    });
}

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);
    //$(conf.form).isValid({}, conf, true);
}

function checkProtocol() {
    var protocol = $("#file_protocol").val();
    $('#video_url, #file_tmp_link_type').each(function(){
        if (protocol != 'custom') {
            $(this).attr('disabled', 'disabled').closest('.form-group').hide();
            if (conf.ignore.indexOf($(this).attr('name')) == -1) {
                conf.ignore.push($(this).attr('name'));
            }
        } else {
            $(this).removeAttr('disabled').closest('.form-group').show();
            if (conf.ignore.indexOf($(this).attr('name')) !== -1) {
                conf.ignore.splice(conf.ignore.indexOf($(this).attr('name')), 1);
            }
        }
    });
}

function checkFileType() {
    var fileType = $("#file_type");
    if (fileType.val() == 'sub') {
        $("#file_quality, #file_volume_level").prop('disabled', 'disabled').closest('.form-group').hide();
        $("#media_info").remove();
        $("#file_form_input_container").addClass('col-sm-offset-2').find('input,select').removeAttr('readonly').removeAttr('disabled');
        $("#modalbox div.devoops-modal-bottom").find('button').removeClass('disabled').removeAttr('disabled');
    } else {
        $("#file_quality, #file_volume_level").removeAttr('disabled').closest('.form-group').show();
    }
}

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

function checkVideoType() {
    $("#add_season_structure").hide();
    $("#add_season").hide();
    if ($("#form_is_series").val() == 1) {
        ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-video-season-list-json", $("#files_container").data(), false);
    } else {
        ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-video-files-list-json", $("#files_container").data(), false);
    }
}

function setUniserial(data) {
    $("#files_container").removeClass().addClass('box').empty();
    $(".serial").removeClass('serial').addClass('uniseries');
    $("#form_year").removeClass("add-video-year");
    $("#form_year_end").attr("disabled", "disabled");
    $("#season_button_container").hide();
    if (typeof (data.data) == 'object') {
        $("#files_container").append($("#files_box_header").html());
        $("#files_container").append($("#files_box_content").html());
        fillFilesData('#files_container', 'filedata');
    }
}

function setUniserialError(obj){
    JSErrorModalBox(obj);
}

function fillFormData(data){
    if (data.result.hasOwnProperty('cover_big')) {
        $('#cover_container').next('img').prop('src', "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-image?url=" + data.result['cover_big'] + '&v='+ $.random(1000000));
    } else {
        $('#cover_container').next('img').prop('src', '');
    }
    $.each([
        'kinopoisk_url',
        'rating_count_kinopoisk',
        'rating_imdb',
        'rating_count_imdb',
        'name',
        'censored',
        'o_name',
        'kinopoisk_id',
        'rating_kinopoisk',
        'year',
        'year_end',
        'duration',
        'country',
        'director',
        'actors',
        'description',
        'comments',
        'rating_mpaa',
        'age',
        'cover_big'
    ], function(i){
        var fieldValue = data.result.hasOwnProperty(this) ? data.result[this] : '';
        var fieldObj = $("#form_" + this);

        if (fieldObj.length != 0) {
            if (fieldObj.get(0).tagName.toLocaleUpperCase() == 'SELECT') {
                fieldObj.find('option[value="' + fieldValue + '"]').prop('selected', 'selected');
                fieldObj.select2(select2Opt);
            } else {
                if (fieldObj.get(0).type && fieldObj.get(0).type.toLocaleUpperCase() == 'CHECKBOX') {
                    fieldObj.prop('checked', !!fieldValue);
                } else {
                    fieldObj.val(fieldValue);
                }
            }
        }
        if (this == 'kinopoisk_url') {
            $('#kinopoisk_url').attr('href', fieldValue);
            $('#kinopoisk_url').html(fieldValue);
        }
    });
    if (!$("#modalbox > div").is(":visible")) {
        $("#modalbox > div").show(50);
    }
    JScloseModalBox();
}

var setSerial = function (data) {
    $("#files_container").removeClass();
    if ($("#filedata").length) {
        $("#files_container").empty();
    }
    $(".uniseries").removeClass('uniseries').addClass('serial');
    $("#form_year").addClass("add-video-year");
    $("#form_year_end").removeAttr("disabled");
    $("#season_button_container").show();

    if (data.data.length == 0) {
        $("#add_season_structure").show();
    } else {
        $("#add_season").show();
    }
    var targetNeighbor = {};
    var existsSeasonBoxCount = $("div[id^='season_']").filter(":not(div[id='season_button_container'])").length;
    var existsSeasonBoxIDs = [];
    $("div[id^='season_']").filter(":not(div[id='season_button_container'])").each(function(){
        existsSeasonBoxIDs.push("#" + $(this).attr('id'));
    });

    var gettingSeasonBoxCount = Object.keys ? Object.keys(data.data).length: -1;
    for (var i in data.data) {
        if (existsSeasonBoxIDs.indexOf("#season_" + data.data[i].season_id) != -1) {
            existsSeasonBoxIDs.splice(existsSeasonBoxIDs.indexOf("#season_" + data.data[i].season_id), 1);
        }
        var seasonBox = $("#season_" + data.data[i].season_id);
        if (seasonBox.length == 0) {
            targetNeighbor.action = 'undefined';
            targetNeighbor.key = 0;
            var neighbors = $("div[id^='season_']:has(div[id^='s_season_'])");
            var season_number = parseInt(data.data[i].season_number, 10);
            $.each(neighbors, function(i) {
                var currNumberS, nextNumberS;
                targetNeighbor.key = i;
                targetNeighbor.action = 'insertAfter';
                currNumberS = parseInt($(this).find("span[data-season-number]").data('season-number'), 10);
                if ( typeof(neighbors[i+1]) != "undefined") {
                    nextNumberS = parseInt($(neighbors[i+1]).find("span[data-season-number]").data('season-number'), 10);
                } else {
                    nextNumberS = false;
                }

                if (season_number < currNumberS) {
                    targetNeighbor.action = 'insertBefore';
                    return false;
                } else if (currNumberS < season_number && nextNumberS !== false && season_number < nextNumberS ) {
                    return false;
                }
            });

            if ( typeof (neighbors[targetNeighbor.key]) != 'undefined' && targetNeighbor.action != 'undefined') {
                seasonBox = $('<div class="box" id="season_' + data.data[i].season_id + '"></div>')[targetNeighbor.action](neighbors[targetNeighbor.key]);
            } else if ($("#other_files").length == 0) {
                seasonBox = $('<div class="box" id="season_' + data.data[i].season_id + '"></div>').appendTo("#files_container");
            } else {
                seasonBox = $('<div class="box" id="season_' + data.data[i].season_id + '"></div>').insertBefore("#other_files");
            }
            seasonBox.data('seasonid', data.data[i].season_id);
            seasonBox.append($("#season_box_header").html());

            seasonBox.find("span[data-season-number]").data("season-number", (typeof(data.data[i].season_number) != 'undefined' ? data.data[i].season_number : 1))
                    .html("{{ 'Season'|trans }} " + (typeof(data.data[i].season_number) != 'undefined' ? data.data[i].season_number : 1));
            seasonBox.find("input[name='season_name']").val((typeof(data.data[i].season_name) != 'undefined' ? data.data[i].season_name : ''));
            seasonBox.find("input[name='season_original_name']").val((typeof(data.data[i].season_original_name) != 'undefined' ? data.data[i].season_original_name : ''));
            seasonBox.append($('<div class="box-content">\n\
                                    <div class="row">\n\
                                        <div class="col-sm-11 col-xs-11 col-sm-offset-1 col-xs-offset-1 no-padding-left">\n\
                                        </div>\n\
                                    </div>\n\
                               </div>'));
            if (existsSeasonBoxCount != gettingSeasonBoxCount) {
                seasonBox.find('.box-content').hide();
            }
        } else {
            seasonBox.find("span[data-season-number]").data("season-number", (typeof(data.data[i].season_number) != 'undefined' ? data.data[i].season_number : 1))
                    .html("{{ 'Season'|trans }} " + (typeof(data.data[i].season_number) != 'undefined' ? data.data[i].season_number : 1));
            seasonBox.find("input[name='season_name']").val((typeof(data.data[i].season_name) != 'undefined' ? data.data[i].season_name : ''));
            seasonBox.find("input[name='season_original_name']").val((typeof(data.data[i].season_original_name) != 'undefined' ? data.data[i].season_original_name : ''));
        }

        seasonBox.find("span[data-series-count]").data("series-count", (typeof(data.data[i].series_count) != 'undefined' ? data.data[i].series_count : 0))
                .html("{{ 'episodes'|trans }} " + (typeof(data.data[i].series_count) != 'undefined' ? data.data[i].series_count : 0));

        targetNeighbor = {action : 'undefined', key: 0};
        var existsSeasonSeriesBoxIDs = [];
        $('div[id^="s_season_' + data.data[i].season_id + '_series_"]').each(function(){
            existsSeasonSeriesBoxIDs.push("#" + $(this).attr('id'));
        });
        for (var j in data.data[i].season_series) {
            var series_id = typeof(data.data[i].season_series[j].series_id) != 'undefined' ? data.data[i].season_series[j].series_id : '';
            if (existsSeasonSeriesBoxIDs.indexOf('#s_season_' + data.data[i].season_id + '_series_' + series_id) != -1) {
                existsSeasonSeriesBoxIDs.splice(existsSeasonSeriesBoxIDs.indexOf('#s_season_' + data.data[i].season_id + '_series_' + series_id), 1);
            }

            var seriesBox = $('#s_season_' + data.data[i].season_id + '_series_' + series_id);

            if (seriesBox.length == 0) {
                targetNeighbor.action = 'undefined';
                targetNeighbor.key = 0;
                var neighborsS = seasonBox.find("div[id^='s_season_']");
                var series_number = parseInt(data.data[i].season_series[j].series_number, 10);
                $.each(neighborsS, function(i) {
                    var currNumberS, nextNumberS;
                    targetNeighbor.key = i;
                    targetNeighbor.action = 'insertAfter';
                    currNumberS = parseInt($(this).find("span[data-series-number]").data('series-number'), 10);
                    if ( typeof(neighborsS[i+1]) != "undefined") {
                        nextNumberS = parseInt($(neighborsS[i+1]).find("span[data-series-number]").data('series-number'), 10);
                    } else {
                        nextNumberS = false;
                    }

                    if (series_number < currNumberS) {
                        targetNeighbor.action = 'insertBefore';
                        return false;
                    } else if (currNumberS < series_number && nextNumberS !== false && series_number < nextNumberS ) {
                        return false;
                    }
                });

                if ( typeof (neighborsS[targetNeighbor.key]) != 'undefined' && targetNeighbor.action != 'undefined') {
                    seriesBox = $('<div class="box" id="s_season_' + data.data[i].season_id + '_series_' + series_id + '"></div>')[targetNeighbor.action](neighborsS[targetNeighbor.key]);
                } else {
                    seriesBox = $('<div class="box" id="s_season_' + data.data[i].season_id + '_series_' + series_id + '"></div>').appendTo(seasonBox.children(".box-content").children(".row").children(".col-sm-11"));
                }

                seriesBox.data('seriesid', series_id);
                seriesBox.append($('#series_box_header').html());
                seriesBox.find("span[data-series-number]").data("series-number", (typeof(data.data[i].season_series[j].series_number) != 'undefined' ? data.data[i].season_series[j].series_number : 1))
                        .html((typeof(data.data[i].season_series[j].series_number) != 'undefined' ? data.data[i].season_series[j].series_number : 1) + " {{ 'episode'|trans }}");
                seriesBox.find("span[data-files-count]").data("files-count", (typeof(data.data[i].season_series[j].series_files) != 'undefined' ? data.data[i].season_series[j].series_files : 0))
                        .html("{{ 'files'|trans }} " + (typeof(data.data[i].season_series[j].series_files) != 'undefined' ? data.data[i].season_series[j].series_files : 0));

                seriesBox.find("input[name='series_name']").val((typeof(data.data[i].season_series[j].series_name) != 'undefined' ? data.data[i].season_series[j].series_name : ''));
                seriesBox.find("input[name='series_original_name']").val((typeof(data.data[i].season_series[j].series_original_name) != 'undefined' ? data.data[i].season_series[j].series_original_name : ''));

                seriesBox.data({'self-id': '#' + seriesBox.attr('id'), 'table-id': 'f_season_' + data.data[i].season_id + '_series_' + series_id + '_filedata'})
                seriesBox.append($("#files_box_content").html());
                seriesBox.find('.box-content').hide();
                //fillFilesData('#' + seriesBox.attr('id'), 'f_season_' + data.data[i].season_id + '_series_' + data.data[i].season_series[j].series_id + '_filedata');
            } else {
                seriesBox.find("span[data-series-number]").data("series-number", (typeof(data.data[i].season_series[j].series_number) != 'undefined' ? data.data[i].season_series[j].series_number : 1))
                        .html((typeof(data.data[i].season_series[j].series_number) != 'undefined' ? data.data[i].season_series[j].series_number : 1) + " {{ 'episode'|trans }}");
                seriesBox.find("span[data-files-count]").data("files-count", (typeof(data.data[i].season_series[j].series_files) != 'undefined' ? data.data[i].season_series[j].series_files : 0))
                        .html("{{ 'files'|trans }} " + (typeof(data.data[i].season_series[j].series_files) != 'undefined' ? data.data[i].season_series[j].series_files : 0));

                seriesBox.find("input[name='series_name']").val((typeof(data.data[i].season_series[j].series_name) != 'undefined' ? data.data[i].season_series[j].series_name : ''));
                seriesBox.find("input[name='series_original_name']").val((typeof(data.data[i].season_series[j].series_original_name) != 'undefined' ? data.data[i].season_series[j].series_original_name : ''));
                if ($("#" + seriesBox.find('table').attr('id')).is(":visible")) {
                    $("#" + seriesBox.find('table').attr('id')).DataTable().ajax.reload();
                }
            }
        }
        $.each(existsSeasonSeriesBoxIDs, function(i, val){
            $(val).remove();
        });
    }

    $.each(existsSeasonBoxIDs, function(i, val){
        $(val).remove();
    });

    if (typeof (data.other_files) != 'undefined' && data.other_files != 0 && $("#other_files").length == 0) {
        $('<div class="box" id="other_files"></div>').appendTo("#files_container");
        $('<div id="other_files_layer"></div>').appendTo("#other_files");
        $('#other_files_layer').css({
            minWidth: '100%',
            minHeight: '100%',
            position: 'absolute',
            top: 0,
            left: 0,
            background: "center rgba(150, 150, 150, 0.3)",
            boxShadow: "0 0 30px 25px rgba(255, 255, 255, 0.7) inset",
            opacity: 0.8,
            zIndex: 400
        });

        $("#other_files").append($("#files_box_header").html());
        $("#other_files").append($("#files_box_content").html());
        fillFilesData('#other_files', 'other_filedata');
        $('#other_files').children('a.collapse-link').find('[data-files-title]').text("{{ 'Other files'|trans }}");
    }
};

var setSerialError = function (obj) {
    JSErrorModalBox(obj);
};

function fillFilesData(target, id) {
    LoadDataTablesScripts(function () {
        /*$(target).append($("#files_box_content").html());*/
        $(target).find('table').attr('id', id);
        $("#" + id).on('xhr.dt', function (e, settings, json) {
            if (typeof (json.data) == 'object') {
                var season_id = '', series_id = '', season_number = '', series_number = '';

                var seasonContainer = $(this).closest('div[id^="season_"]');
                if (seasonContainer.length) {
                    season_id = seasonContainer.data('seasonid');
                    season_number = seasonContainer.find("span[data-season-number]").data("season-number");
                }
                var seriesContainer = $(this).closest('div[id^="s_season_"]');
                if (seriesContainer.length) {
                    series_id = seriesContainer.data('seriesid');
                    series_number = seriesContainer.find("span[data-series-number]").data("series-number");
                }
                var video_id = $("#files_container").data('video_id');
                for (var i in json.data) {
                    var id = typeof(json.data[i].id) != 'undefined' ? json.data[i].id : '';

                    var status = parseInt(json.data[i].status, 10);
                    var accessed = parseInt(json.data[i].accessed, 10);
                    var file_name = json.data[i].file_name;

                    json.data[i].languages = json.data[i].languages.join(", ");

                    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 class='main_ajax no_context_menu' href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-one-video-file-json' data-id='" + id + "' data-video_id='" + video_id + "' data-season_id='" + season_id + "' data-series_id='" + series_id + "' data-season_number='" + season_number + "' data-series_number='" + series_number + "' data-file_name='" + file_name + "'>\n\
                                                            <span>{{ 'Edit'|trans }}</span>\n\
                                                        </a>\n\
                                                    </li>";
                    if (id != 0 ) {
                        json.data[i].operations += "<li>\n\
                                                        <a class='main_ajax no_context_menu' " + (id == 0 ? "disabled='disabled'" : '') + " href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/toggle-video-accessed' data-accessed='" + (accessed != 0 ? 0 : 1) + "' data-id='" + id + "' data-video_id='" + video_id + "'  data-season_id='" + season_id + "' data-series_id='" + series_id + "'>\n\
                                                            <span>" + ( accessed == "1" ? "{{ 'Unpublish'|trans }}" : "{{ 'Publish'|trans }}") + "</span>\n\
                                                        </a>\n\
                                                    </li>";
                    }
                    if (id != 0 ) {
                        json.data[i].operations += "<li>\n\
                                                        <a class='main_ajax no_context_menu' " + (id == 0 ? "disabled='disabled'" : '') + " href='{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/remove-video-data' data-id='" + id + "' data-video_id='" + video_id + "' data-season_id='" + season_id + "' data-series_id='" + series_id + "'>\n\
                                                            <span>{{ 'Remove'|trans }}</span>\n\
                                                        </a>\n\
                                                    </li>";
                    }
                    json.data[i].operations += "</ul>\n\
                                            </div>";

                    json.data[i].status = accessed != 0 ? "<span class='txt-success'>{{ 'Published'|trans }}</span>" : "<span class='txt-danger'>{{ 'Unpublished'|trans }}</span>";
                    json.data[i].status += (status == 0 ? "<br><span class=''>{{ 'Not available on storages'|trans }}</span>" : "");
                    json.data[i].volume_level = parseInt(json.data[i].volume_level, 10) * 5;
                }
                var counter = !isNaN(i) ? (parseInt(i, 10) + 1) : 0;
                $(target).children('a.collapse-link').find('[data-files-count]').text('{{ 'files'|trans }} ' + counter);
                $(target).find('.dataTables_processing:first-of-type').hide('');
            }

            if (json.old_url) {
                addOldURLNote(target, json.old_url);
            } else if ($(target).find('.box-header button.btn-old-url').length == 0) {
                $(target).find('.box-header button.btn-old-url').remove();
            }

        }).dataTable({
            "processing": false,
            "serverSide": false,
            "ajax": {
                "url": "{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-video-files-list-json",
                "data": function (d) {
                    if ($("#files_container").data('video_id')) {
                        d['video_id'] = $("#files_container").data('video_id');
                    }
                    var season = $(target).closest("div[id^='season_']").find('[data-season-number]');
                    if (season.length && season.data('season-number')) {
                        d['seasonnumber'] = season.data('season-number');
                    }
                    var series = $(target).closest("div[id^='s_season_']").find('[data-series-number]');
                    if (series.length && series.data('series-number')) {
                        d['seriesnumber'] = $(series).data('series-number');
                    }
                }
            },
            "deferLoading": [{#{{ app.recordsFiltered }}, {{ app.totalRecords }}#}],
            "language": {
                "url": "{{ app.datatable_lang_file }}"
            },
            {% if attribute(app, 'dropdownAttribute') is defined %}
            {{ main_macro.get_datatable_column(app['dropdownAttribute']) }}
            {% endif %}
            "bFilter": true,
            "bPaginate": true,
            "bInfo": true,
            "aoColumnDefs": [
                {className: "action-menu", "targets": [-1]}
            ]
        }).prev('.dataTables_processing').hide('');
    });
}

function addOldURLNote(target, old_url){
    if ($(target).find('.box-header button.btn-old-url').length == 0) {
        var button = $(target).find('.box-header button:first');
        var newButton = button.clone(true);
        newButton.text("{{ 'Old data'|trans }}").data('old-url', old_url).addClass('btn-old-url');
        button.before(newButton);
    }
}

var deleteCover = function (data) {
    if (typeof (data.id)) {
        $("#" + data.id).data('id', 'new');
    }
    JSSuccessModalBox(data);
};

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

var closeModalBox = function () {
    var dataTable = ($("#season_id").length != 0 && $("#series_id").length != 0) ? 'f_season_' + $("#season_id").val() + '_series_' + $("#series_id").val() + '_filedata' : "filedata";
    if ($("#" + dataTable).length != 0) {
        dataTableUpdate({datatable: dataTable});
    } else {
        JScloseModalBox();
    }
};

var emptyFileContainer = function (data) {
    $('#files_container').empty();
};

var dataTableUpdate = function (data) {
    if (data.msg || data.error) {
        JSSuccessModalBox(data);
    } else {
        JScloseModalBox();
    }
    if (data.btn_old_url_remove) {
        $("#" + data.datatable).closest('.box-content').parent('div').find('.box-header button.btn-old-url').remove();
    }
    if ($("#" + data.datatable).length != 0) {
        $("#" + data.datatable).DataTable().ajax.reload();
    } else {
        JSErrorModalBox({msg: "{{ 'Something wrong. Please reload page.'|trans }}"});
    }
};

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

var fillModalBoxFilesData = function (data, localFilling) {

    if (!localFilling) {
        $("#modalbox").hide();
        $("#modalbox").data('complete', 1);
        $('#modalbox').find('.modal-header-name span').text("{{ 'Edit file'|trans }}");
        $('#modalbox').find('.devoops-modal-inner').html($("#modal_save_form_body").text());
        $('#modalbox').find('.devoops-modal-bottom').html($("#modal_save_form_buttons").text());
    }

    var fields = {file_id: 'id', video_id: 'video_id', season_id: 'season_id', series_id: 'series_id', status: 'status'};
    for (var key in fields) {
        var field = fields[key];
        if (typeof(data.data[field]) != 'undefined' && data.data[field]) {
            $("#" + key).val(data.data[field]);
        } else if(!localFilling) {
            $("#" + key).remove();
        }

    }

    var fields = {
        file_type: 'file_type',
        file_protocol: 'protocol',
        file_quality: 'quality',
        file_volume_level: 'volume_level',
        file_accessed: 'accessed',
        file_tmp_link_type: 'tmp_link_type'
    };
    for (var key in fields) {
        var field = fields[key];
        if (typeof(data.data[field]) != 'undefined' && data.data[field]) {
            $("#" + key + " option").prop('selected', false).removeAttr('selected');
            $("#" + key).find('option[value="' + data.data[field] + '"]').prop('selected', 'selected');
        }
        if(!localFilling) {
            $("#" + key).removeAttr('readonly').removeAttr('disabled');
        }
    }
    $('#modalbox').show();

    $('#file_type').select2(select2Opt);
    $('#file_quality').select2(select2Opt);
    $('#file_volume_level').select2(select2Opt);
    $('#file_protocol').select2(select2Opt);
    $('#file_accessed').select2(select2Opt);
    $('#file_tmp_link_type').select2(select2OptPH);

    if (!localFilling) {
        setFileLanguagesSelect();
    }

    if (typeof(data.data.languages) != 'undefined' && data.data.languages instanceof Array && data.data.languages.length) {
        if (localFilling) {
            $("#fileLangCloneList li.select2-selection__choice").trigger("click");
        }
        $("#file_languages").val(data.data.languages).trigger("change");
        var resultList = {};
        $.each( $("#file_languages").data().select2.data(), function(i){
            resultList[this.id] = this.text;
        });
        $.each(data.data.languages, function(i){
            if (typeof resultList[this] != 'undefined') {
                var liTmpl = $('<li class="select2-selection__choice" title=""><span role="presentation" class="select2-selection__choice__remove">×</span></li>').insertBefore($("#fileLangCloneList").find('li.select2-search'));
                liTmpl.attr('title', resultList[this]);
                liTmpl.find('span').after(resultList[this]);
                liTmpl.data('val', this);
            }
        });
        if ($("#fileLangCloneList").height() >= $('#file_languages').next().height()) {
            $("#fileLangCloneList").parent().css({paddingTop: $("#fileLangCloneList").height() - $('#file_languages').next().height() + 'px'});
        } else {
            $("#fileLangCloneList").find('.select2-selection').css({minHeight: $('#file_languages').next().height() + 'px'})
        }
    }
    if (typeof(data.data.file_name) != 'undefined' && data.data.file_name) {
        $("#file_name").val(data.data.file_name);
    }
    if (typeof(data.data.url) != 'undefined' && data.data.url) {
        $("#video_url").val(data.data.url);
    }
    checkProtocol();
    checkFileType();
    if (!localFilling) {
        getMediaInfo();
    }
};

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

var getMediaInfo = function() {
    var sendData = {};
    if ($("#file_type").val() != 'sub') {
        $("#file_form_input_container").find("input,select").each(function(i){ //.not(":disabled")
            var val = this.tagName.toUpperCase() == 'INPUT' ? $(this).val(): $(this).find('option:selected').val();
            if (val) {
                sendData[$(this).attr('name')] = val;
            }
        });
        $("#file_form_input_container").find('input,select').prop('readonly', 'readonly').prop('disabled', 'disabled');
        $("#modalbox div.devoops-modal-bottom").find('button').addClass('disabled').prop('disabled', 'disabled');
        if (!$("#media_info").length) {
            $("#file_form_input_container").removeClass('col-sm-offset-2').after($("#media_info_body").html()).delay(1000).promise().done(function(){
                $("#media_info").css({opacity: 1, width: '29%'});
            });
        } else {
            cleanMediaInfo();
        }

        ajaxPostSend("{{ app.request_context.baseUrl }}/{{ app.controller_alias }}/get-media-info-json", sendData, false, false, true);
    } else {
        checkProtocol();
        checkFileType();
    }
};

var setMediaInfo = function(data){
    cleanMediaInfo();
    if (data.id && $('#file_id').length == 0) {
        $("#video_id").before("<input type='hidden' class='own_fields form-control' name='id' id='file_id' value='' readonly='readonly'>");
    }
    if($('#file_id').length && (!$('#file_id').val() || $('#file_id').val() == '0')) {
        $('#file_id').val(data.id ? data.id: 0);
    }
    if (data.data) {
        $("#media_info").addClass('filled').find('button').removeClass('disabled').prop('disabled', false).removeAttr('disabled');
        var infoField = $($("#media_info_info").html()).prependTo("#media_info");
        if (!data.error){
            infoField.addClass('bg-default').addClass('txt-default').text("{{ 'Media info from source'|trans }}");
        }
        if (data.data.datatable) {
            $("#" + data.data.datatable).DataTable().ajax.reload();
            delete data.data.datatable;
        }
        for(var key in data.data){
            var infoField = $($("#media_info_info").html()).insertAfter(infoField);
            var textVal = data.data[key];
            var textLabel = words && words[key] ? words[key]: key;
            if (key == 'languages') {
                textVal = [];
                $.each(data.data[key], function(){
                    textVal.push($("#file_" + key + " option[value='" + this + "']").text());
                });
                textVal = textVal.join(', ');
            } else if (key == 'quality') {
                textVal = $("#file_" + key + " option[value='" + textVal + "']").text();
            }
            infoField.addClass('bg-default').addClass('txt-default').text(textLabel + ": " + textVal);
            infoField.data({'info-key': key, 'info-val': data.data[key] instanceof Array? data.data[key].join(','): data.data[key]});
        }
    }
};

var setMediaInfoError = function(data) {
    setMediaInfo(data);
    $("#media_info").addClass('filled');
    var infoField = $($("#media_info_info").html()).prependTo("#media_info");
    infoField.addClass('bg-warning').addClass('txt-danger').text("{{ 'No media info'|trans }}");
    var addMessage = data.msg || data.error;
    if (addMessage) {
        var infoField2 = $($("#media_info_info").html()).insertAfter(infoField);
        infoField2.addClass('bg-warning').addClass('txt-danger').text(addMessage);
    }
};

var cleanMediaInfo = function(){
    $("#file_form_input_container").find('input,select').prop('readonly', false).prop('disabled', false).removeAttr('readonly').removeAttr('disabled');
    $("#modalbox div.devoops-modal-bottom").find('button').removeClass('disabled').prop('disabled', false).removeAttr('disabled');
    $("#media_info").removeClass('filled').find('button').addClass('disabled').prop('disabled', 'disabled');
    $("#media_info").children().not('button').remove();
    checkProtocol();
    checkFileType();
};

var errAction = function(data){
    setMediaInfoError({});
    JSErrorModalBox(data);
};

var emptyFunction = function(){}
