var AddFilesModule = (function () {

    var options = {};
    var $_fields = {};
    var $addFilesContainer = {};
    var _inputIdGen;

    var _classes = {
        FILE_INPUT_CONTAINER: '.js-add-files__input-container',
        LABEL_LIST: '.js-add-files__label-list',
        ADD_FILE_BUTTON: '.js-add-files__button_add',
        ADD_FILE_BUTTON_TEXT: '.js-add-files__button-text'
    };

    var _eventAddFile = function () {
        if (this.files && this.files[0]) {
            var counter = Object.keys($_fields).length;
            var cnt = Object.keys(this.files).length;
            // В safari Object.keys(input.files) добавляет в конец массива 'length'
            {
                if (Object.keys(this.files)[cnt - 1] == 'length') {
                    cnt--;
                }
            }
            for (var i = 0; i < cnt; i++) {
                if (!(counter + i + 1 <= options['max_file_count'])) {
                    alert('Превышено максимальное количество файлов.');
                    this.value = '';
                    return false;
                }
                if (this.files[i].size > 4194304) {
                    alert('Размер файла не должен превышать 4Mb');
                    this.value = '';
                    return false;
                }
            }
            for (i = 0; i < cnt; i++) {
                _addLabelForNewFile(i, this);
            }

            _addField();
        }
    };

    var _addLabelForNewFile = function (fileNum, input) {
        var id = _inputIdGen.getID();

        var fileName = input.files[fileNum].name;
        var size = input.files[fileNum].size;

        var $fileName = $('<input type="hidden" name="inputName__' + id + '" value ="sizeFile' + fileName + size + '">');

        _addLabel(fileName, id, $fileName, false);
    };

    var _getFileIco = function (fileName) {
        var len = fileName.length;
        var symb3 = fileName.substr(len - 3, len).toLowerCase();
        var symb4 = fileName.substr(len - 4, len).toLowerCase();
        var ico = '';
        if ($.inArray(symb3, ['doc', 'xls', 'rtf', 'txt']) != -1 || $.inArray(symb4, ['docx', 'xlsx']) != -1) {
            ico = 'doc';
        } else if ($.inArray(symb3, ['zip', 'rar']) != -1) {
            ico = 'zip';
        } else if ($.inArray(symb3, ['png', 'jpg', 'gif', 'psd']) != -1 || $.inArray(symb4, ['jpeg']) != -1) {
            ico = 'image';
        } else if ($.inArray(symb3, ['mp3', 'wav', 'avi']) != -1) {
            ico = 'audio';
        } else {
            ico = 'zip';
        }

        return ico;
    };

    var _addLabel = function (fileName, id, $extAppend, isOld) {
        var ico = _getFileIco(fileName);
        var allow = _isAllow(fileName);
        var $fileNameBlock = $('<span class="dib v-align-m ml10 '+(allow?'':'color-red')+'">').text(fileName);

        var $delFileBlock = "";
        if(allow) {
            $delFileBlock = $('<a class="remove-file-link" data-old="' + isOld + '" data-id="' + id + '"></a>');
        }
        else {
            $delFileBlock = $('<a class="ml10 cur color-red" style="display:block;float:right;" data-old="' + isOld + '" data-id="' + id + '">Тип файла не поддерживается</a>');
        }
        $delFileBlock.bind('click', _deleteFile);

        var $labelContainer = $('<div class="mt10 file-item"><i class="ico-file-' + ico + ' dib v-align-m"></i></div>');
        $labelContainer.append($fileNameBlock).append($delFileBlock).append($extAppend);

        $_fields[id] = $labelContainer;

        $addFilesContainer.find(_classes.LABEL_LIST).append($labelContainer);
    };

    var _addField = function () {
        var $field = $('<input name="' + options['input-name'] + '[]" type="file" multiple>');

        $field.bind('change', _eventAddFile);
        $addFilesContainer.find(_classes.FILE_INPUT_CONTAINER).append($field);
        _setButtonText();
    };

    var _setEventHandlers = function () {
        $addFilesContainer.on('click', _classes.ADD_FILE_BUTTON, function () {
            $addFilesContainer.find(_classes.FILE_INPUT_CONTAINER + ' input:last-child').trigger('click');
        });
    };

    var _deleteFile = function () {
        if ($(this).data('old') == true) {
            $addFilesContainer.find(_classes.FILE_INPUT_CONTAINER).prepend($('<input>').attr({
                type: 'hidden',
                name: 'remove_files[]',
                value: $(this).data('id')
            }));
        }

        var id = $(this).data('id');
        $_fields[id].remove();
		    delete $_fields[id];

        _setButtonText();
    };

    var _setButtonText = function () {
        var $addBtn = $addFilesContainer.find(_classes.ADD_FILE_BUTTON);
        if (Object.keys($_fields).length > 1) {
            $addFilesContainer.find(_classes.ADD_FILE_BUTTON_TEXT).text($addBtn.data('withFiles'));
        } else {
            $addFilesContainer.find(_classes.ADD_FILE_BUTTON_TEXT).text($addBtn.data('withoutFiles'));
        }
    };

    var _showLoadedFile = function (file) {
        _addLabel(file.fname, file.id, {}, true);
        _setButtonText();
    };

    var _isAllow = function (fileName) {
        var len = fileName.length;
        var symb3 = fileName.substr(len - 3, len).toLowerCase();
        return !($.inArray(symb3, ["exe", "com", "dll", "sys", "drv", "bin", "ovl", "ovy", "dot"]) != -1);
    };

    return {
        init: function (o) {
            _inputIdGen = new IDGenerator('id-');

            options = o;
            $addFilesContainer = $('.js-add-files');
            _setEventHandlers();
            _addField();

            if (typeof options.files !== 'undefined') {
                for (var i = 0; i < options.files.length; i++) {
                    _showLoadedFile(options.files[i]);
                }
            }
        }
    }
})();