WRMCB=function(e){var c=console;if(c&&c.log&&c.error){c.log('Error running batched script.');c.error(e);}}
;
try {
/* module-key = 'com.tempoplugin.tempo-accounts:accounts-customfield-resource', location = '/com/tempoplugin/accounts/link/data/account-link-model.js' */
define('tempo-accounts/data/link-model',
    ['jquery',
        'tempo-core/backbone',
        'tempo-accounts/context-path'],
    function ($, Backbone, contextPath) {
        return Backbone.Model.extend({
            initialize: function (options) {
                this.projectId = options.projectId;
                this.getDefault = options.getDefault;
            },

            url: function () {
                var url = contextPath() + '/rest/tempo-accounts/1/link';
                if (this.id) {
                    url += '/' + this.id;
                } else if (this.projectId) {
                    url += '/project/' + this.projectId;
                    if (this.getDefault) {
                        url += '/default';
                    }
                }
                return url;
            }
        });
    }
);
}catch(e){WRMCB(e)};
;
try {
/* module-key = 'com.tempoplugin.tempo-accounts:accounts-customfield-resource', location = '/com/tempoplugin/accounts/link/data/account-link-collection.js' */
define('tempo-accounts/data/link-collection',
    ['jquery',
        'tempo-core/backbone',
        'tempo-accounts/data/link-model',
        'tempo-accounts/context-path'],
    function ($, Backbone, AccountLinkModel, contextPath) {
        return Backbone.Collection.extend({

            model: AccountLinkModel,

            initialize: function (models, options) {
                this.accountId = options.accountId;
            },

            url: function () {
                var url = contextPath() + '/rest/tempo-accounts/1/';
                if (this.accountId) {
                    url += 'account/' + this.accountId + '/link';
                } else {
                    url += 'link/picker';
                }
                return url;
            },

            comparator: function (model) {
                if (model.get('name')) {
                    return model.get('name');
                }
            }
        });
    }
);

}catch(e){WRMCB(e)};
;
try {
/* module-key = 'com.tempoplugin.tempo-accounts:accounts-customfield-resource', location = '/com/tempoplugin/accounts/account/data/account-model.js' */
define('tempo-accounts/data/account-model',
    ['jquery',
        'tempo-core/backbone',
        'tempo-accounts/constants',
        'tempo-accounts/data/link-collection',
        'tempo-accounts/context-path'],
    function ($, Backbone, Constants, AccountLinkCollection, contextPath) {
        var Status = Constants.Status;

        return Backbone.Model.extend({

            initialize: function (options) {
                this.id = options.id;
                this.setGlobal = typeof options.setGlobal !== 'undefined' ? options.setGlobal : false;
                this.issueKey = options.issueKey;
                this.accountId = options.accountId;
            },

            url: function () {
                var url = contextPath() + '/rest/tempo-accounts/1/account';
                if (this.id) {
                    url += '/' + this.id;
                    if (this.setGlobal) {
                        url += '/global/' + this.get('global');
                    }
                } else if (this.issueKey) {
                    url += '/issue/' + this.issueKey + '/current';
                } else if (this.accountId) {
                    url += '/' + this.accountId;
                }
                return url;
            },

            parse: function (response) {
                if (response) {
                    if (response.links) {
                        response.links = new AccountLinkCollection(response.links, {});
                    }

                    if (response.rateTable && typeof response.rateTable.name === 'undefined') {
                        response.rateTable.name = response.rateTable.parent.name;
                    }

                    switch (response.status) {
                        case Status.OPEN.status :
                            response.formattedStatus = Status.OPEN;
                            break;
                        case Status.CLOSED.status :
                            response.formattedStatus = Status.CLOSED;
                            break;
                        case Status.ARCHIVED.status :
                            response.formattedStatus = Status.ARCHIVED;
                            break;
                    }
                    return response;
                }
            },

            saveMonthlyBudget: function (monthlybudget) {
                var dfd = new $.Deferred();
                this.set('monthlybudget', monthlybudget);
                this.save().done(function () {
                    dfd.resolve();
                });
                return dfd.promise();
            },

            fetchLinks: function () {
                var dfd = new $.Deferred();
                if (this.get('global') || this.get('links')) {
                    dfd.resolve();
                } else {
                    var linkCollection = new AccountLinkCollection([], {
                        accountId: this.id
                    });
                    this.set('links', linkCollection);  // To make sure we are not fetching links again while waiting for response
                    var self = this;
                    linkCollection.fetch({
                        success: function () {
                            self.set('links', linkCollection);
                            dfd.resolve();
                        }
                    });
                }
                return dfd.promise();
            }
        });
    }
);

}catch(e){WRMCB(e)};
;
try {
/* module-key = 'com.tempoplugin.tempo-accounts:accounts-customfield-resource', location = '/com/tempoplugin/accounts/customfield/view/account-customfield-picker.js' */
require(['jquery',
        'underscore',
        'tempo-core/backbone',
        'tempo-accounts/data/link-model',
        'tempo-accounts/data/account-model',
        'tempo-accounts/ajs-meta',
        'tempo-accounts/context-path',
        'tempo-accounts/jira-events'],
    function ($, _, Backbone, AccountLinkModel, AccountModel, Meta, contextPath, Events) {

        var CustomFieldPickerView = Backbone.View.extend({

            initialize: function (options) {
                this.projectId = options.projectId;
                this.defaultMaxResults = parseInt(Meta.get('default-max-results'), 10);
                this.defaultAccountDfd = this.getDefaultAccount();
                this.preselectedAccountOptionDfd = this.getPreselectedAccountOption();
                this.isRequired = this.$el.data('required-field');
                this.isSubtask = $('input[id=tempo-isSubtask]').val();
            },

            getDefaultAccount: function () {
                var self = this;
                var dfd = new $.Deferred();
                var defaultLink = new AccountLinkModel({
                    projectId: this.projectId,
                    getDefault: true
                });
                defaultLink.fetch({
                    success: function () {
                        if (defaultLink.isNew()) {
                            dfd.resolve();
                        } else {
                            self.defaultAccount = new AccountModel({
                                id: defaultLink.get('accountId')
                            });
                            self.defaultAccount.fetch({
                                success: function () {
                                    dfd.resolve();
                                }
                            });
                        }
                    }
                });
                return dfd.promise();
            },

            getPreselectedAccountOption: function () {
                var self = this;
                var dfd = new $.Deferred();
                var isCreateDialog = $('#create-issue-submit').length === 1 || $('#issue-create-submit').length === 1;
                this.defaultAccountDfd.done(function () {
                    if ($('input[name=parentIssueId]').val()) {
                        // Ignore default account / only account when creating subtask
                        dfd.resolve();
                    } else {
                        if (self.defaultAccount && isCreateDialog) {
                            self.preselectedAccountOption = self.accountToOption(self.defaultAccount.attributes);
                            dfd.resolve();
                        } else {
                            // When CREATING a new issue, if the project is only linked to one account, even if it is
                            // not set as default account, it has to be preselected. (TMAC-667)
                            if (isCreateDialog) {
                                $.get(self.getUrl() + '&limit=2').done(function (response) {
                                    if (response.totalRecords === 1) {
                                        self.preselectedAccountOption = self.accountToOption(response.accounts[0]);
                                    }
                                    dfd.resolve();
                                });
                            } else {
                                dfd.resolve();
                            }
                        }
                    }
                });
                return dfd.promise();
            },

            getNoValueOption: function () {
                return this.getOption(-1, "\u041f\u0443\u0441\u0442\u043e");
            },

            getInheritValueOption: function () {
                return this.getOption(0, "\u0423\u043d\u0430\u0441\u043b\u0435\u0434\u043e\u0432\u0430\u043d\u043e \u043e\u0442 \u0440\u043e\u0434\u0438\u0442\u0435\u043b\u044f");
            },

            getHeadingOption: function (title) {
                return {
                    text: title
                };
            },

            accountToOption: function (account) {
                return this.getOption(account.id, account.name + ' (' + account.key + ')');
            },

            getOption: function (value, title) {
                return {
                    id: value,
                    text: title
                };
            },

            getUrl: function () {
                var params = $.param({
                    tqlQuery: 'status=OPEN AND (project=' + this.projectId + ' OR project=GLOBAL)'
                });
                return contextPath() + '/rest/tempo-accounts/1/account/search?' + params;
            },

            resetLimitAndOffset: function () {
                this.limit = 15;
                this.offset = 0;
            },

            updateStatistics: function (data) {
                this.totalRecords = data.totalRecords;
                this.totalPages = data.totalPages;
                this.pageSize = data.pageSize;
                this.remaining = this.totalRecords - (this.pageSize + this.offset);
                if (this.remaining < 0) {
                    this.remaining = 0;
                }
                this.loadMoreSize = 4 * (this.pageSize + this.offset);
                if (this.loadMoreSize > this.defaultMaxResults) {
                    this.loadMoreSize = this.defaultMaxResults;
                }
                if (this.loadMoreSize > this.remaining) {
                    this.loadMoreSize = this.remaining;
                }
                this.offset += this.limit;
                this.limit = this.loadMoreSize;
            },

            render: function () {
                var self = this;
                this.defaultAccountDfd.done(function () {
                    $('.ta-customfield-spinner').hide();
                    var $select = $('input.ta-customfield-input');
                    $select.auiSelect2({
                        dropdownCssClass: 'ta-customfield-select aui-list',
                        ajax: {
                            url: self.getUrl(),
                            cache: 'true',
                            dataType: 'json',
                            data: function (query) {
                                if (query !== self.query) {
                                    // reset limit and offset when changing search query by input text
                                    self.resetLimitAndOffset();
                                }
                                self.query = query;
                                return {
                                    query: query,
                                    limit: self.limit,
                                    offset: self.offset
                                };
                            },
                            results: function (data, page) {
                                self.updateStatistics(data);
                                var results = [];
                                if (page === 1) {
                                    if (!self.isRequired) {
                                        results.push(self.getNoValueOption());
                                    }

                                    if(self.isSubtask) {
                                        results.push(self.getInheritValueOption());
                                    }

                                    if (self.defaultAccount) {
                                        results.push(self.getHeadingOption("\u0421\u0447\u0451\u0442 \u043f\u043e \u0443\u043c\u043e\u043b\u0447\u0430\u043d\u0438\u044e"));
                                        results.push(self.accountToOption(self.defaultAccount.attributes));
                                    }

                                    if (!_.isEmpty(data.accounts)) {
                                        results.push(self.getHeadingOption("\u0421\u0432\u044f\u0437\u0430\u043d\u043d\u044b\u0435 \u0441 \u044d\u0442\u0438\u043c \u043f\u0440\u043e\u0435\u043a\u0442\u043e\u043c \u0430\u043a\u043a\u0430\u0443\u043d\u0442\u044b"));
                                    }
                                }
                                _.each(data.accounts, function (account) {
                                    results.push(self.accountToOption(account));
                                });
                                return {
                                    results: results,
                                    more: (self.remaining > 0)
                                };
                            }
                        },
                        initSelection: function (element, callback) {
                            var data = {};
                            if (!_.isEmpty(element.val()) && !_.isEmpty(element.attr('title'))) {
                                data = self.getOption(element.val(), element.attr('title'));
                            }
                            callback(data, element);
                        },
                        formatSelection: function (selected) {
                            if (_.isEmpty(selected)) {
                                var select = this.element.siblings('select.tempo-account-customfield');
                                var selectedOption = select.find('option:selected');
                                var selectedValue = selectedOption.val();
                                var selectedText = selectedOption.text();
                                if (!_.isEmpty(selectedValue)) {
                                    selected = self.getOption(selectedValue, selectedText);
                                } else {
                                    self.preselectedAccountOptionDfd.done(function () {
                                        if (self.preselectedAccountOption) {
                                            $select.select2('data', self.preselectedAccountOption);
                                        } else {
                                            if (!self.isRequired) {
                                                $select.select2('data', self.getNoValueOption());
                                            }
                                        }
                                    });
                                }
                            } else {
                                // Needed to resolve TMA-12163
                                this.element.attr('title', selected.text);
                            }
                            return _.escape(selected.text);
                        },
                        formatResult: function (object) {
                            if (!object.id) {
                                return '<span class=\'ta-customfield-heading\'>' + _.escape(object.text) + '</span>';
                            }
                            return _.escape(object.text);
                        },
                        formatResultCssClass: function () {
                            return 'aui-list-item';
                        },
                        formatLoadMore: function () {
                            return AJS.format("\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442\u0441\u044f \u0435\u0449\u0435 {0} (\u0432\u0441\u0435\u0433\u043e {1})", self.loadMoreSize, self.totalRecords);
                        },
                        formatSearching: function () {
                            return "\u0417\u0430\u0433\u0440\u0443\u0437\u043a\u0430...";
                        },
                        formatNoMatches: function () {
                            return "\u041d\u0435\u0442 \u0441\u043e\u0432\u043f\u0430\u0434\u0435\u043d\u0438\u0439";
                        }
                    });

                    $select.on('select2-open', function () {
                        self.resetLimitAndOffset();
                        setTimeout(function () {
                            if ($('.select2-container.ta-customfield-input').length === 0) {
                                // When using custom field in JIRA Service Desk issue, then it is not possible to edit inline (disable the dropdown for now) TMAC-822
                                $('.select2-drop.ta-customfield-select').hide();
                            }
                        }, 100);
                    });

                    $select.on('select2-highlight', function () {
                        $('.ta-customfield-select li').removeClass('active');
                        $('.ta-customfield-select li.select2-highlighted').addClass('active');
                    });

                    if ($select.parent().parent('.inline-edit-fields').length > 0 && $select.siblings('.inline-edit-error').length === 0) {
                        // open the dropdown on when entering inline edit mode
                        $select.select2('open');
                    }
                });
                return this;
            }
        });

        function loadCustomField() {
            _.each($('input.ta-customfield-input'), function (field) {
                new CustomFieldPickerView({
                    el: '#' + field.id,
                    projectId: Meta.get('project-id')
                }).render();
            });
        }

        loadCustomField(); // JIRA.bind does not load in all cases (i.e. Move issue, JIRA Capture)

        JIRA.bind(Events.NEW_CONTENT_ADDED, function (e, context, reason) {
            loadCustomField();
        });
    }
);

}catch(e){WRMCB(e)};