﻿function CustomerIssueFiles() {
    var page = 0;
    var _this = this;
   

    this.prefix = "customer_issue_";

    this.countUploaded = 0;
    this.AjaxRemoveFile = "/customer-issue-file/remove";
    
    this.init = function ()
    {
        $(".remove").live("click", function () {
            if (confirm("Удалить этот файл?")) {
                var num = parseInt($(this).parent().attr("id").substr(_this.prefix.length));
                var id = $(".identify", $(this).parent()).val();
                _this.remove(id, num);
            };
        });
        this.countUploaded = $(".item", this.container()).length;
    }

    this.container = function () 
    {
        return $(".file-list");
    }


    this.getById = function (id) {
        return $("#" + _this.prefix + id);
    }

    this.load = function (loadPath, id) {
        var ajaxData = {
            id: id
        };
        $.ajax({
            type: "POST",
            url: loadPath,
            data: ajaxData,
            success: function (data) {
                if (data.result == "ok") {
                    $.each(data.data, function (i, item) {
                        _this.create(item);
                    });
                }
                if (data.result == "error") {
                    _this.showErrors(data.errors);
                }
            },
            error: function () {
                alert("Внутренняя ошибка");
            }
        });
    }

    this.create = function (data) {
        var item = $("<div/>").attr("class", "item").attr("id", this.prefix + _this.countUploaded).appendTo(_this.container());
        var mimetype = $("<div/>").attr("class", "mime").appendTo(item);
        var img = $("<img/>").attr("src", data.MimeTypeIcon).appendTo(mimetype);
        img.attr("title", data.FileName);
        var remove = $("<div/>").attr("class", "remove").appendTo(item);
        _this.createHidden(data, item);
    }

    this.createHidden = function (data, item) {
        $("<input>").attr("class", "identify").attr("type", "hidden").attr("name", "CustomerIssueFiles[" + _this.countUploaded + "].ID").attr("id", "CustomerIssueFiles_" + _this.countUploaded + "__ID").attr("value", data.ID).appendTo(item);
        _this.countUploaded++;
    }

    this.remove = function (Id, countItem) 
    {
        ajaxData = {
            id: Id
        }
        $.ajax({
            type: "POST",
            url: _this.AjaxRemoveFile,
            data: ajaxData,
            success: function (data) {
                if (data.result == "ok") {
                    _this.getById(countItem).remove();
                    for (var i = countItem + 1; i < _this.countUploaded; i++)
                    {
                        //функция пересчета аттрибутов name и id
                        _this.recalculate(i);
                    }
                    _this.countUploaded--;
                }
                if (data.result == "error") {
                    _this.showErrors(data.errors);
                }
            },
            error: function () {
                alert("Внутренняя ошибка");
            }
        });
    }

    this.recalculate = function (number) {
        var prevNumber = number - 1;
        //скобки "[" и "]" которые присутствуют в id DOM-объекта в jquery селекторе необходим экранировать двойным обратным слэшем \\
        _this.getById(number).attr("id", _this.prefix + prevNumber);
        $("#CustomerIssueFiles_" + number + "__ID").attr("id", "CustomerIssueFiles_" + prevNumber + "__ID").attr("name", "CustomerIssueFiles[" + prevNumber + "].ID");
    }

    this.showErrors = function (errors) {
        var errorContainer = $("#issue-osx-modal-content .errors");
        $.each(errors, function (i, item) {
            $("<div>").attr("class", "line err").text(item.Message).appendTo(errorContainer);
        });
    }
}

var customerIssueFiles;
$().ready(function () 
{
    customerIssueFiles = new CustomerIssueFiles();
    customerIssueFiles.init();
});
