window.beforeApplyColumns = function () {
    if ($('#tb_mode').val() == 'tree') {
        window.location = base + 'asset.ivp/tree';
        return false;
    }
    return true;
};

function importAssets() {
    var dlg = openDialog('assetimport.ivp', '', { height: 400, width: 600 });
    dlg.callback = function () { reloadTable(); }
    return false;
}

function reloadTable(callback) {
    $(tableRootDiv).load(tableUrl(), { nolayout: true, timestamp: new Date().toString() }, function () {
        initTable();
        if (callback && typeof (callback) === "function") {
            callback();
        }
    });
}

window.afterInitTable = function () {
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(95));
}

//#region ChangeFields

//#endregion


var AssetTriggerActions = {
    init: function () {
        var that = this;
        $(document).on('change', 'input.rowid', function (e) {
            that.checkDisableOptions();
        });

        return this;
    },

    checkDisableOptions: function () {
        var that = this;
        var $options = $('#assettriggeractions > option[value!=""]');
        $.each($options, function (i, v) {
            v.disabled = that['disabled_' + v.value]();
        });
    },

    trigger: function () {
        var $select = $('#assettriggeractions');
        var action = $select.val();
        $select.val('');
        this['trigger_' + action]();
    },

    trigger_changeFields: function () {
        var that = this;

        function changeFieldsSubmit() {
            var $form = $('#changefieldsform');

            //Валидируем форму и заполняем displayedfields
            var formIsValid = true;
            var displayedFields = '';

            //cтандартные поля (валидация не нужна)
            var defaultFields = ['parentid', 'ownerid', 'comment'];
            defaultFields.forEach(function (field) {
                if ($('#' + field).parents('.field').css('display') != 'none')
                    displayedFields += field + ',';
            });
            //дополнительные поля
            $form.find('[id^="field"]').each(function () {
                var $e = $(this);
                var displayed = $e.parents('.field').css('display') != 'none';

                if (displayed) {
                    displayedFields += $e.attr('id') + ',';
                    if (!$e.valid()) formIsValid = false;
                }
            });

            if (displayedFields == '') return true;//Если не выбраны поля, то просто закрываем форму
            $('#displayedFields').val(displayedFields);

            if (!formIsValid) return false;
            $.post(base + 'assettable.ivp/ChangeFieldsSubmit', $form.serialize(), function (response) {
                alert(JSON.parse(response));
                reloadTable();
                selectedIds = new Array(); //Снятие выделения строк
                that.checkDisableOptions();
            });
        }

        function changeFieldsInitialize() {
            $('#dialog .field').each(function (i, e) {
                var $e = $(e);
                if ($e.is('[is-group-field]')) {
                    return;
                }

                if (($e.find('input').length < 1 && $e.find('select').length < 1 && $e.find('textarea').length < 1) || $e.find('input[type="file"]').length > 0) {
                    //Убираем с формы всё что не инпуты, селекты или текстарии, а так же инпуты типа файл
                    $e.remove();
                    return;
                }
                var textarea = $e.find('textarea');
                if (textarea.length > 0) {
                    textarea.val('').addClass('width98');
                }
                $e.find('input[type="text"]').addClass('width98');
                var numeric = $e.find('input.numeric');
                if (numeric.length > 0) {
                    numeric.addClass('numeric100');
                }
                $e.hide();
                var $l = $($e.find('label'));
                var id = $l.prop('for');
                var selector = '$(&quot;#' + $l.prop('for') + '&quot;).closest(&quot;.field&quot;)';
                $e.after('<div style="margin: 0 0 7px"><a href="#" field-id="' + id + '" class="nounderline" onclick="' + selector + '.show(); $(this).parent().hide(); return false;">' +
                    $l.text() +
                    '<img title="' + CommonResources.Change + '" src="img/pencil10.gif">' + '</a></div>');
                $l.append('<img title="' + CommonResources.Cancel + '" src="img/minus.png">');
                $l.css('cursor', 'pointer');
                $l.on('click', function () {
                    var chechBox = $l.find('input[type="checkbox"]');
                    if (chechBox.length > 0 && chechBox.is(":hover")) { return true; }
                    $('a[field-id="' + id + '"]').parent().show();
                    $('#' + id).closest('.field').hide();
                    return false;
                });
            });
        }

        $.post(base + 'assettable.ivp/ChangeFieldsForm/', { ids: selectedIds.join(',') }, function (response) {
            createModalDialog(AssetResources.ChangingFields, response, changeFieldsSubmit, changeFieldsInitialize, { width: 600, minWidth: 600 });
        });
    },

    disabled_changeFields: function () {
        return selectedIds.length == 0;
    }

}.init();


function expandGroupElement(link, forceShow) {
    var $link = $(link);
    var targetId = $link.attr('data-target');
    var $target = $('#' + targetId);
    var $img = $(link).find('img');
    var show = (forceShow != undefined && forceShow) || !$target.is('[group-expanded]');
    if (show) {
        $target.attr('group-expanded', true);
        $img.attr('src', 'img/tree/minus.gif');
        $target.show();
    }
    else {
        $target.removeAttr('group-expanded');
        $img.attr('src', 'img/tree/plus.gif');
        $target.hide();
    }

    return false;
}

function delAssets(options) {
    if (selectedIds.length == 0) { alert(TableResources.NoRecordsSelected); return false; }
    if (!confirm(TableResources.SureDeleteRecords)) return false;

    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString(),withChildren:true };
    if (options != null) $.extend(params, options);
    $.ajax({
        type:"POST",
        url:  base + tableController() +'deletecheck',
        data: params,
        dataType: 'json',
        success: function (data, textStatus, jqXHR) {
            if (data && data.hasChildren) {
                var dialog = $('<div id="assetdialog"></div>').dialog({
                    autoOpen: false,
                    open: function () {

                    },
                    width: 'auto',
                    maxWidth: screen.width - 25,
                    modal: true,
                    position: { my: "center" },
                    resizable: false,
                    close: function () {
                        $(this).dialog("destroy");
                        $(this).remove();
                    }
                });
                $(".ui-dialog .ui-dialog-title").html(AssetResources.DeleteAssets);
                var $body = $('<div class="formbody">' + AssetResources.HasChild +
                    '</div><div class="formbottom">' +
                    '<button onclick="delAssetsCase(true)">' + AssetResources.DeleteWithChildren + '</button>' +
                    '<button onclick="delAssetsCase(false)">' + AssetResources.DeleteOnlySelected + '</button>' +
                    '<button onclick="$(\'#assetdialog\').dialog(\'close\')">' + CommonResources.Cancel + '</button>' +
                    "</div>")
                dialog.append($body);
                dialog.dialog('open');
            }
            else {
                var url = base + tableController() + 'Delete';
                selectedIds.length = 0;
                $(tableRootDiv).load(url, params, initTable);
            }
        }
    });
  
    return false;
}

function delAssetsCase(withChildren) {
    var params = { id: selectedIds.join(','), nolayout: true, timestamp: new Date().toString(), withChildren: withChildren };
    var url = base + tableController() + 'Delete';
    selectedIds.length = 0;
    $('#assetdialog').dialog('close');
    $(tableRootDiv).load(url, params, initTable);
}