WRMCB=function(e){var c=console;if(c&&c.log&&c.error){c.log('Error running batched script.');c.error(e);}}
;
try {
/* module-key = 'is.origo.jira.tempo-plugin:tempo-global', location = 'com/tempoplugin/js/tempo.global.js' */
require(['jquery',
        'underscore',
        'tempo-core/moment',
        'tempo/context-path',
        'tempo/analytics'],
    function ($, _, moment, contextPath) {
    window.tempo = window.tempo || {};

    var DATE_FORMAT = moment().toMomentFormatString(AJS.Meta.get('date-dmy')),
        TIME_FORMAT = AJS.Meta.get('date-time') || 'HH:mm',
        DATE_TIME_FORMAT = AJS.Meta.get('date-complete') || DATE_FORMAT + ' ' + TIME_FORMAT,
        ANSI_DATE_FORMAT = "YYYY-MM-DD",
        ANSI_DATE_TIME_FORMAT = 'YYYY-MM-DDTHH:mm',
        invalidPeriodMessage = "\u041f\u0435\u0440\u0438\u043e\u0434 \u043d\u0435\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0442\u0435\u043b\u0435\u043d",
        unauthorizedAjaxMessage = "\u0412\u044b \u0434\u043e\u043b\u0436\u043d\u044b \u0432\u043e\u0439\u0442\u0438 \u0432 JIRA \u0434\u043b\u044f \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u0438\u044f \u044d\u0442\u043e\u0433\u043e \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044f. \u0421\u0435\u0441\u0441\u0438\u044f, \u0432\u043e\u0437\u043c\u043e\u0436\u043d\u043e, \u0438\u0441\u0442\u0435\u043a\u043b\u0430!",
        MATCHING_STRATEGY = "(|.*?(\\s+|\\())({0})(.*)";


    $.extend($.expr[':'], {
        focus: function (element) {
            return element === document.activeElement;
        }
    });

    var dateStringToANSI = function(dateString) {
        return parseDate(dateString).format(ANSI_DATE_FORMAT);
    };

    var parseDate = function (dateString) {
        return moment(dateString, DATE_FORMAT);
    };

    var parseDateTime = function (dateString) {
        return moment(dateString, DATE_TIME_FORMAT);
    };

    function calculateAvailability(form, user, from, to) {
        if (!user || form.find('input.availability').length !== 1) {
            return;
        }

        var data;
        var url = contextPath() + '/rest/tempo-rest/2.0/user/getUser';

        if (!form.find('.showperiod').is(':checked') || to.val() === '') {
            to = from;
        }
        data = {  from: dateStringToANSI(from.val()),  to: dateStringToANSI(to.val()), username: user };

        $.ajax({
            url : url,
            cache : false,
            data : data,
            success : function (result) {
                form.find('input.availability').val(result.availableString);
                form.find('input.workingdays').val(result.workDaysString);

            },
            error : function (request, status, errorThrown) {
                alert(status);
            }
        });
    }

    function processValidationResult(result, form) {
        var errors = form.find('ul.error-list'),
            isValid = true;
        var response, error;

        $(result).find('submit-result').each(function () {
            response = $(this);
            if (response.attr('valid') === 'false') {
                response.find('errors').each(function () {
                    error = $(this);
                    errors.append($('<li/>').text(error.find("errorMessage").text()));
                });
                isValid = false;
            }
        });
        return isValid;
    }

    function validatePeriod(dateFrom, dateTo, withStartTime) {
        var from = withStartTime ? parseDate(dateFrom) : parseDateTime(dateFrom),
            to = parseDate(dateTo);

        return !from.isAfter(to);
    }

    function createAccountGroups(group, label, dropdown) {
        if (group !== undefined && group.length > 0) {
            var i, optgroup = $("<optgroup>").attr("label", label);
            for (i = 0; i < group.length; i++) {
                group[i].appendTo(optgroup);
            }
            optgroup.appendTo(dropdown);
        }
    }

    function populateDropdown(dropdown, data, url) {
        if (data.error !== undefined && data.error !== null && data.error !== '') {
            alert("Error in TDD query: " + data.error);
            return;
        }

        dropdown.empty();
        var accountGroup = [];
        var globalAccountGroup = [];

        $.each(data.values, function (i, dataItem) {
            var element = $("<option/>").val(dataItem.key).text(dataItem.value);

            if (dataItem.global === true) {
                globalAccountGroup.push(element);
            } else if (dataItem.global === false) {
                accountGroup.push(element);
            } else {
                element.appendTo(dropdown);
            }
        });

        createAccountGroups(accountGroup, "\u0410\u043a\u043a\u0430\u0443\u043d\u0442\u044b", dropdown);
        createAccountGroups(globalAccountGroup, "\u0413\u043b\u043e\u0431\u0430\u043b\u044c\u043d\u044b\u0435 \u0430\u043a\u043a\u0430\u0443\u043d\u0442\u044b", dropdown);

        var isAccountAttribute = (accountGroup.length + globalAccountGroup.length) > 0;
        setDynamicDropdownValue(dropdown, data, isAccountAttribute);
    }

    function setDynamicDropdownValue(dropdown, data, isAccountAttribute) {
        var dropdownValue;
        var worklogValue = dropdown.attr('worklogValue');

        if (worklogValue) {
            /* EXISTING WORKLOGS */
            dropdownValue = worklogValue;

            // Display full attribute name in inline-editable span in report/list views
            var selectedDropdownValue = _.find(data.values, function (dataItem) {
                return dataItem.key === dropdownValue;
            });
            var spanText = selectedDropdownValue ? selectedDropdownValue.value : worklogValue;
            dropdown.siblings('span.edit-container').text(spanText);

            if (!selectedDropdownValue && isAccountAttribute) {
                $.ajax({
                    url: contextPath() + '/rest/tempo-accounts/1/account/key/' + worklogValue,
                    success: function (account) {
                        if (account) {
                            spanText = account.key + ' - ' + account.name;
                            dropdown.siblings('span.edit-container').text(spanText);
                        }
                    }
                });
            }
        } else if (!isAccountAttribute) {
            /* NEW WORKLOGS */
            // Non-account attributes default to preselected value
            dropdownValue = dropdown.attr('selectedValue') || "";
        } else {
            /* NEW WORKLOGS */
            // Otherwise check if issue in question has an account assigned
            var selectedItem = _.find(data.values, function(dataItem) { return dataItem.selected === true; });
            dropdownValue = selectedItem ? selectedItem.key : "";
            // if no key then it is the 'please select' value
            if (selectedItem && selectedItem.key) {
              dropdown.siblings('span.edit-container').text(selectedItem.value);
            }
        }
        dropdown.val(dropdownValue);
    }

    var dropdownCache = {},
        dropdownCachePromises = {};

    function getExternalData(dropdown, url) {
        var cacheKey = dropdown[0].id;
        var promise = dropdownCachePromises[cacheKey];
        if (promise === undefined) {
            // NB. we can only do async requests in the reports, not in "add" since
            // worklog attributes can depend on each other. Checking for the issueKey is
            // simply checking if we are in the reports or not
            var asyncRequests = !tempo.isEmptyString(dropdown.attr("issueKey"));
//            console.log("Getting external data for: " + url + " async: " + asyncRequests);
            promise = $.ajax({
                async: asyncRequests,
                url: encodeURI(url),
                dataType: 'jsonp',
                success: function (data) {
                    dropdownCache[cacheKey] = data;
                },
                error: function () {
                    dropdownCache[cacheKey] = {values: []};
                }
            });
            dropdownCachePromises[cacheKey] = promise;
        }
        return promise;
    }

    var state = {
        dirty: false,
        locked : false,
        popup_title : {}
    };

    var blanket = $('<div id="tempo-blanket"/>').css('z-index', '2000').css('height', '100%').hide(),
        spinner = {
            show : function (index) {
                blanket.addClass('aui-blanket').css('z-index', index || '2000').show();

                if ($.fancybox) {
                    $.fancybox.showActivity();
                } else {
                    $('div.aui-loading').show();
                }
            },
            hide: function () {
                blanket.removeClass('aui-blanket').css('z-index', '2000').hide();
                $('div.aui-loading').hide();
                if ($.fancybox) {
                    $.fancybox.hideActivity();
                }
            }
        };

    var reload = function (url) {
        spinner.show();
        if (url) {
            window.location = url;
        } else {
            window.location.reload();
        }
        return this;
    };

    function isEmptyString(field) {
        return field === undefined || field === null || field.length === 0;
    }

    var noop = function () {
        return undefined;
    };

    var widget = {
        Dropdown: AJS.Dropdown || AJS.DropDown,
        formatSuccess: jira.app.fragments ? jira.app.fragments.issueActionsFragment : JIRA.FRAGMENTS.issueActionsFragment,
        FormPopup: AJS.FormPopup || (JIRA ? JIRA.FormDialog : noop),
        containDropdown: AJS.containDropdown || (JIRA ? JIRA.containDropdown : noop),
        sessionStorage: jira.app.session ? jira.app.session.storage : JIRA.SessionStorage
    };

    function extractErrorMessage(responseXML) {
        var responseError = JSON.parse(responseXML);
        var error = _.values(responseError.errors);
        if (error) {
            return error;
        }
        return responseXML;
    }

    function showHoursLabel() {
        var label, tmp, txt;
        var form = $(this).closest('form');

        form.find('.enddate').toggle(this.checked);
        form.find('input[name=date]').trigger('change');

        label = form.find('label.timepicker-label');
        tmp = label.attr('tmp');
        txt = label.text();
        label.attr('tmp', txt);
        label.text(tmp);
    }

    $.fn.fixDirtyForm = function () {
        /* fix for JIRA 4.4.1 and greater */
        $(this).addClass("ajs-dirty-warning-exempt");
        /* fix for JIRA 4.4 and below */
        if (AJS.DIRTY_FORM_VALUE) {
            return this.data(AJS.DIRTY_FORM_VALUE, null);
        }
        return this;
    };

    $.fn.cleanFormValidation = function () {
        var form = $(this),
            errors = form.find('ul.error-list');

        form.find(':input:visible')
            .removeClass("error-field")
            .removeClass("valid");
        errors.empty();
        return this;
    };

    $.fn.resetFormFields = function () {
        var form = $(this);
        form.find('.resetable :checkbox').attr('checked', false);
        form.find('.resetable select, .resetable textarea, .resetable input[type=text]').val('').change();
        form.find('.enddate').hide();
        form.find('select.tempoDynamicDropDown').empty().removeAttr('selectedValue');
        return this;
    };

    $.fn.TempoSingleSelect = AJS.SingleSelect.extend({
        // Fix to prevent premature form-submission by the AJS.SingleSelect (TMA-3418)
        submitForm : function () {
            if (!this.suggestionsVisible) {
                this.handleFreeInput();
                if (this.options.submitHandler) {
                    this.options.submitHandler();
                }
            }
        },

        // Set width of input-field and dropdown (TMA-3803)
        setFieldWidth: function (width, dropdownWidth) {
            dropdownWidth = dropdownWidth || width;

            this.$container.css({
                width: width,
                minWidth: width
            });
            this.$field.width(width);

            this.dropdownController.$layer.css({
                width: dropdownWidth,
                minWidth: dropdownWidth
            });

        },

        setDropdownWidthForTimesheet: function (options) {
            if (options && options.timesheet && this.$container) {
                this.setFieldWidth(205, 500);
            }
        },

        setAjaxOptionsQueryParam: function (key, value) {
            if (this.options === undefined) {
                this.options = {};
            }
            if (this.options.ajaxOptions === undefined) {
                this.options.ajaxOptions = {};
            }
            if (this.options.ajaxOptions.data === undefined) {
                this.options.ajaxOptions.data = {};
            }
            this.options.ajaxOptions.data[key] = value;
        }
    });

    $.fn.tempoFormatAccountPicker = function (response) {
        var ret = [],
            groupDescriptor;

        $(response).each(function (i, results) {
            if (results.group !== null && results.group !== undefined) {
                $(results.group).each(function (j, items) {
                    groupDescriptor = new AJS.GroupDescriptor({
                        weight: j, // order or groups in suggestions dropdown
                        id: "tempo-report-account-search-" + j,
                        replace: true,
                        label: items.title // Heading of group
                    });
                    $(items.item).each(function () {
                        groupDescriptor.addItem(new AJS.ItemDescriptor({
                            value: this.type + '-' + this.id, // value of item added to select
                            label: this.name, // title of lozenge
                            html: this.html,
                            allowDuplicate: false
                        }));
                    });
                    ret.push(groupDescriptor);
                });
            }
        });
        return ret;
    };

    $.fn.tempoFilterPicker = function (options) {
        var $this = $(this),
            picker = new $.fn.TempoSingleSelect({
                element: $this,
                showDropdownButton: true,
                removeOnUnSelect: false,
                matchingStrategy : MATCHING_STRATEGY,
                submitInputVal: true,
                noQueryNoRequest: false,
                ajaxOptions: {
                    url: contextPath() + "/rest/tempo-rest/2.0/filters/picker",
                    query: true, // keep going back to the server for each keystroke
                    minQueryLength: 1,
                    data: {},
                    formatResponse: function (response) {
                        var groupDescriptor, label,
                            ret = [];

                        if (options && options.timesheet) {
                            picker.setDropdownWidthForTimesheet(options);
                            var defaultGroup = new AJS.GroupDescriptor({
                                weight: 0, // order or groups in suggestions dropdown
                                id: "tempo-default-suggested",
                                replace: true
                            });
                            defaultGroup.addItem(new AJS.ItemDescriptor({
                                value: "-1001", // no filter selected
                                label: "\u0420\u0430\u0441\u043f\u0438\u0441\u0430\u043d\u0438\u0435 \u043f\u043e\u043b\u044c\u0437\u043e\u0432\u0430\u0442\u0435\u043b\u0435\u0439",
                                allowDuplicate: false
                            }));

                            ret.push(defaultGroup);
                        }

                        $(response).each(function (i, suggestions) {
                            groupDescriptor = new AJS.GroupDescriptor({
                                weight: i + 1, // order or groups in suggestions dropdown
                                id: "tempo-report-filter-suggested-" + 1,
                                replace: true,
                                label: "\u0424\u0438\u043b\u044c\u0442\u0440\u044b" // Heading of group
                            });
                            $(suggestions.filters).each(function () {
                                label = this.name;
                                if (this.description) {
                                    label += " (" + this.description + ")";
                                }
                                groupDescriptor.addItem(new AJS.ItemDescriptor({
                                    value: String(this.id), // value of item added to select
                                    label: label, // title of lozenge
                                    allowDuplicate: false
                                }));
                            });
                            ret.push(groupDescriptor);
                        });
                        return ret;
                    }
                }
            });
    };

    $.fn.tempoFormatAdvancedSearchResponse = function (response) {
        var ret = [],
            groupDescriptor;

        $(response).each(function (i, results) {
            $(results.group).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-search-" + j,
                    replace: true,
                    label: items.title // Heading of group
                });
                $(items.item).each(function () {
                    groupDescriptor.addItem(new AJS.ItemDescriptor({
                        value: String(this.id), // value of item added to select
                        label: this.name, // title of lozenge
                        html: this.html,
                        allowDuplicate: false
                    }));
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoAdvancedTimesheetPicker = function (options) {
        var $this = $(this),
            picker = new $.fn.TempoSingleSelect({
                element: $this,
                showDropdownButton: true,
                matchingStrategy : MATCHING_STRATEGY,
                removeOnUnSelect: false,
                submitInputVal: true,
                noQueryNoRequest: false,
                ajaxOptions: {
                    url: contextPath() + "/rest/tempo-rest/2.0/search/picker",
                    query: true, // keep going back to the sever for each keystroke
                    minQueryLength: 1,
                    data: {},
                    formatResponse: $.fn.tempoFormatAdvancedSearchResponse
                }
            });

        picker.setDropdownWidthForTimesheet(options);
    };

    $.fn.tempoFormatIssueResponse = function (response) {
        var ret = [],
            groupDescriptor;

        $(response).each(function (i, results) {
            $(results.group).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-issue-search-" + j,
                    replace: true,
                    label: items.title // Heading of group
                });
                $(items.item).each(function () {
                    groupDescriptor.addItem(new AJS.ItemDescriptor({
                        value: this.key, // value of item added to select
                        label: this.key + ' - ' + this.name, // title of lozenge
//                        html: this.html,
                        allowDuplicate: false,
                        title: this.name,
                        icon: contextPath() + this.icon
                    }));
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoIssuePicker = function (options) {
        var $this = $(this);
        var $form = $this.closest('form');

        var actionType = $form.find('input[name=planning]').val() === "true" ? "planTime" : "logTime";

        if (options !== undefined && options.actionType !== undefined){
            actionType = options.actionType;
        }

        var username = options !== undefined && options.username !== undefined
            ? options.username
            : "";

        var issueType = options !== undefined && options.type !== undefined
            ? options.type
            : "";

        var picker = new $.fn.TempoSingleSelect({
            submitHandler : options ? options.submitHandler : null,
            element: $this,
            showDropdownButton: true,
            removeOnUnSelect: false,
            submitInputVal: true,
            noQueryNoRequest: false,
            ajaxOptions: {
                url: contextPath() + "/rest/tempo-rest/2.0/issues/picker/" + issueType,
                query: true, // keep going back to the sever for each keystroke
                minQueryLength: 1,
                data: {username: username, issueType: issueType, actionType: actionType},
                formatResponse: $.fn.tempoFormatIssueResponse
            }
        });
        picker.setDropdownWidthForTimesheet(options);
        $this.data('picker', picker);
        return picker;
    };

    // todo: refactor all these Format functions - they are all almost identical
    $.fn.tempoFormatVersionResponse = function (response) {
        var ret = [],
            groupDescriptor;
        $(response).each(function (i, results) {
            $(results).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-version-search-" + j,
                    replace: true,
                    label: items.name // Heading of group
                });
                $(items.versions).each(function () {
                    if (this.released === false && this.id > 0) {
                        groupDescriptor.addItem(new AJS.ItemDescriptor({
                            value: this.id, // value of item added to select
                            label: this.name,
                            html: this.html,
                            id: this.id,
                            allowDuplicate: false,
                            title: this.name
                        }));
                    }
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoPlanActivityPicker = function (options) {
        var projectPicker = $(this).closest("form").find('.tempo-project-picker');
        var projectId = projectPicker.val() ? projectPicker.val()[0] : 0;

        var $this = $(this);
        var picker = new $.fn.TempoSingleSelect({
            element: $this,
            showDropdownButton: true,
            removeOnUnSelect: false,
            submitInputVal: true,
            noQueryNoRequest: false,
            ajaxOptions: {
                url: contextPath() + "/rest/tempo-rest/2.0/project/" + projectId,
                query: true, // keep going back to the sever for each keystroke
                minQueryLength: 1,
                data: {},
                formatResponse: options.formatResponse
            }
        });
        picker.setDropdownWidthForTimesheet(options);
    };

    $.fn.tempoFormatComponentResponse = function (response) {
        var ret = [],
            groupDescriptor;
        $(response).each(function (i, results) {
            $(results).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-component-search-" + j,
                    replace: true,
                    label: items.name // Heading of group
                });
                $(items.components).each(function () {
                    groupDescriptor.addItem(new AJS.ItemDescriptor({
                        value: this.id, // value of item added to select
                        label: this.name,
                        html: this.html,
                        id: this.id,
                        allowDuplicate: false,
                        title: this.name
                    }));
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoFormatProjectResponse = function (response) {
        var ret = [],
            groupDescriptor;
        $(response).each(function (i, results) {
            $(results.group).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-project-search-" + j,
                    replace: true,
                    label: items.title // Heading of group
                });
                $(items.item).each(function () {
                    groupDescriptor.addItem(new AJS.ItemDescriptor({
                        value: String(this.id), // value of item added to select
                        label: this.name + " (" + this.key + ")", // title of lozenge
                        html: this.html,
                        allowDuplicate: false,
                        title: this.name,
                        icon: contextPath() + this.icon
                    }));
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoFormatSingleProjectResponse = function (response) {
        var ret = [],
            groupDescriptor;
        $(response).each(function (i, results) {
            $(results.group).each(function (j, items) {
                groupDescriptor = new AJS.GroupDescriptor({
                    weight: j, // order or groups in suggestions dropdown
                    id: "tempo-report-project-search-" + j,
                    replace: true,
                    label: items.title // Heading of group
                });
                $(items.item).each(function () {
                    groupDescriptor.addItem(new AJS.ItemDescriptor({
                        value: "" + this.id, // value of item added to select
                        label: this.name + " (" + this.key + ")", // title of lozenge
                        html: this.html,
                        allowDuplicate: false,
                        title: this.name,
                        icon: contextPath() + this.icon
                    }));
                });
                ret.push(groupDescriptor);
            });
        });
        return ret;
    };

    $.fn.tempoSingleProjectPicker = function (options) {
        $.each(this, function () {  //project, version, component tab
            var $this, picker;
            $this = $(this);
            picker = new $.fn.TempoSingleSelect({
                element: $this,
                matchingStrategy: MATCHING_STRATEGY,
                showDropdownButton: true,
                removeOnUnSelect: false,
                submitInputVal: true,
                noQueryNoRequest: false,
                ajaxOptions: {
                    url: contextPath() + "/rest/tempo-rest/2.0/projects/picker",
                    query: true, // keep going back to the sever for each keystroke
                    minQueryLength: 1,
                    data: {},
                    formatResponse: $.fn.tempoFormatSingleProjectResponse
                }
            });
            picker.setDropdownWidthForTimesheet(options);
        });
    };

    $.fn.tempoFormatUserResponse = function (response) {
        return [new AJS.GroupDescriptor({
            items: _.map(_.sortBy(response.users, "label"), function (user) {
                return new AJS.ItemDescriptor({
                    highlighted: true,
                    html: user.html,
                    label: user.displayName,
                    value: String(user.name),
                    title: user.displayName,
                    icon: user.avatarUrl
                });
            })
        })];
    };

    $.fn.tempoSingleUserPicker = function (options) {
        var type = "";
        var $this = $(this);
        var $form = $this.closest('form');
        var actionType = $form.find('input[name=planning]').val() === "true" ? "planTime" : "logTime";

        if (options !== undefined) {
            if (options.type !== undefined) {
                type = options.type;
            }
            if (options.actionType !== undefined) {
                actionType = options.actionType;
            }
        }

        $(this).each(function () {
            var $this = $(this);

            var userPicker = new $.fn.TempoSingleSelect({
                submitHandler : options ? options.submitHandler : null,
                element: $this,
                showDropdownButton: true,
                matchingStrategy : MATCHING_STRATEGY,
                removeOnUnSelect: false,
                submitInputVal: true,
                noQueryNoRequest: true,
                ajaxOptions: {
                    url: contextPath() + "/rest/tempo-rest/2.0/users/picker/" + type,
                    query: true, // keep going back to the server for each keystroke
                    minQueryLength: 2,
                    data: {
                        showAvatar: true,
                        actionType: actionType,
                        includeInactive: false
                    },
                    formatResponse: $.fn.tempoFormatUserResponse
                }
            });

            userPicker.setDropdownWidthForTimesheet(options);
            $this.data('userPicker', userPicker);
            $this.bind('change', function () {
                var form = $this.closest('form');
                var user = form.find(':input[name=user]').val();
                var from = form.find('input[name=date]');
                var to = form.find('input[name=enddate]');
                calculateAvailability(form, user, from, to);
            });
        });
    };

    $.fn.tempoFormatTeamResponse = function (response) {
        var ret = [],
            groupDescriptor;

        $(response).each(function (i, suggestions) {
            groupDescriptor = new AJS.GroupDescriptor({
                weight: i, // order or groups in suggestions dropdown
                id: "tempo-report-team-search",
                replace: true//,
                //  label: suggestions.footer // Heading of group
            });
            $(suggestions.teams).each(function () {
                groupDescriptor.addItem(new AJS.ItemDescriptor({
                    value: String(this.id), // value of item added to select
                    label: this.name, // title of lozenge
                    html: this.html,
                    allowDuplicate: false
                }));
            });
            ret.push(groupDescriptor);
        });
        return ret;
    };

    $.fn.tempoSingleActivityPicker = function (options) {
        var $this = $(this),
            data = {projectId : function () {
                return $('#tempo-report-project').val();
            }};

        var picker = new $.fn.TempoSingleSelect({
            element: $this,
            showDropdownButton: true,
            removeOnUnSelect: false,
            matchingStrategy : MATCHING_STRATEGY,
            submitInputVal: true,
            noQueryNoRequest: false,
            ajaxOptions: {
                url: contextPath() + "/rest/tempo-rest/2.0/activities/picker",
                query: true, // keep going back to the sever for each keystroke
                minQueryLength: 1,
                data: data,
                formatResponse: function (response) {
                    var ret = [],
                        groupDescriptor;

                    $(response).each(function (i, results) {
                        $(results.group).each(function (j, items) {
                            groupDescriptor = new AJS.GroupDescriptor({
                                weight: j, // order or groups in suggestions dropdown
                                id: "tempo-report-activity-search" + j,
                                replace: true,
                                label: items.title // Heading of group
                            });
                            $(items.item).each(function () {
                                groupDescriptor.addItem(new AJS.ItemDescriptor({
                                    value: this.type + '-' + this.id, // value of item added to select
                                    label: this.name, // title of lozenge
                                    html: this.html,
                                    allowDuplicate: false
                                }));
                            });
                            ret.push(groupDescriptor);
                            picker.setDropdownWidthForTimesheet(options);
                        });
                    });
                    return ret;
                }
            }
        });
    };

    var _navigateDatePicker = function(picker, keycode) {
        switch (keycode) {
            // Esc, Enter or Tab
            case 13:
            case 27:
            case 9:
                picker.hide();
                break;
        }
    };

    var currentTime = function(timezoneOffset){
        var mom = moment().utc().utcOffset(timezoneOffset);
        var stripZone = mom.format('YYYY-MM-DDTHH:mm:ss.SSS');
        var time = moment(stripZone);
        return time.hours()+':'+time.minutes();
    };

    worklogTimePicker = function($field){
        var timePickerOptions = {
            zindex: 9999, //Must be higher than logwork dialog.
            timeFormat: TIME_FORMAT,
            interval: 30,
            defaultTime: $field.val() || currentTime($field.data('offset-minutes') || 0)
        };
        $field.timepicker(timePickerOptions);
    };

    $.extend(tempo, {
        ansiFormat: ANSI_DATE_FORMAT,
        DATE_FORMAT: DATE_FORMAT,
        MATCHING_STRATEGY: MATCHING_STRATEGY,
        spinner: spinner,
        reload: reload,
        state: state,
        widget: widget,
        isEmptyString: isEmptyString,
        blanket: blanket,
        moment: moment,
    });

    $(function () {
        // More license details shown in License Details page and About Tempo popup
        function moreLicenseDetailsToggle() {
            var moreLicenseLink = $("span.more-license-details").last(),
                pluginsData = moreLicenseLink.parent().find("ul.license-details");

            pluginsData.hide(); // hide by default

            moreLicenseLink.bind('click', function () {
                pluginsData.toggle(); // toggle visibility of plugin list
                moreLicenseLink.toggleClass("active");
            });
        }

        function contextRefresh(context) {

        }

        moreLicenseDetailsToggle();

        // Needed to display widget FormPopup for old dialogs
        var TempoMediumPopupForm = new tempo.widget.FormPopup({
            id: "tempo-medium-form",
            trigger: "a.tempoaction-open-medium-form",
            ajaxOptions: {
                data: {
                    inline: true,
                    decorator: "dialog"
                }
            },
            initCallback: function () {
                hideFunction = this.hide;
            },
            widthClass: "medium",
            onContentRefresh: function () {
                this.get$popupContent();
            }
        });

        // Needed to display widget FormPopup for old dialogs
        var TempoSmallPopupForm = new tempo.widget.FormPopup({
            id: "tempo-small-form",
            trigger: "a.tempoaction-open-small-form",
            ajaxOptions: {
                data: {
                    inline: true,
                    decorator: "dialog"
                }
            },
            initCallback: function () {
                hideFunction = this.hide;
            },
            widthClass: "small",
            onContentRefresh: function () {
                this.get$popupContent();
            }
        });

        // Needed to display widget FormPopup for old dialogs
        var TempoLargePopupForm = new tempo.widget.FormPopup({
            id: "tempo-large-form",
            trigger: "#tempo-about-popup-mlink, .tempoaction-open-large-form",
            ajaxOptions: {
                data: {
                    inline: true,
                    decorator: "dialog"
                }
            },
            initCallback: function () {
                hideFunction = this.hide;
            },
            width: 750,
            onContentRefresh: function () {
                this.get$popupContent();
                moreLicenseDetailsToggle();
            }
        });

        // Needed to display widget FormPopup for old dialogs
        var TempoActionForm = new tempo.widget.FormPopup({
            id: "tempo-acton-form",
            trigger: "a.tempoaction-open-dialog-form",
            ajaxOptions: {
                data: {
                    inline: true,
                    decorator: "dialog"
                }
            },
            initCallback: function () {
                hideFunction = this.hide;
            },
            widthClass: "medium",
            onContentRefresh: function () {
                this.get$popupContent();
            }
        });

    });

    // open Tempo Help Center in new tab.
        (function() {
            setTimeout(function() {
                $("#tempo-help--mlink_lnk").attr("target", "_blank");
            }, 1000)
        })()

});

}catch(e){WRMCB(e)};
;
try {
/* module-key = 'is.origo.jira.tempo-plugin:tempo-global', location = 'com/tempoplugin/js/tempo.worklog.v2.js' */
define('tempo/global-worklog-dialog', [
    'jquery',
    'underscore',
    'tempo/context-path',
    'tempo/ajs-meta',
    'tempo/jira-events',
    'tempo/analytics'
], function ($, _, contextPath, Meta, Events, Analytics) {

    function trackLogWorkWithShortcut() {
        // Log work by using shortcut
        Analytics.addActionTrackingInfo(Analytics.Constants.VALUES.ACTIONS.KEYBOARD_SHORTCUT);
    }

    function shortcutOpenDialog() {
        if ($('#worklogForm')[0]) {
            // do nothing if worklog form already exists in the dom
            return;
        }
        var timesheetLink = $('#timesheet-mlink'); // Timesheets is enabled and user has Tempo Time Tracking permission
        if (timesheetLink.length > 0) {
            var issueKey = jira.app.issue.getIssueKey();
            if (issueKey) {
                // We have an issue
                $.get(contextPath() + '/rest/api/2/mypermissions/?issueKey=' + issueKey, function (response) {
                    if (response.permissions.WORK_ON_ISSUES.havePermission) {
                        triggerWorklogDialog({originTaskId: issueKey});
                        trackLogWorkWithShortcut();
                    }
                });
            } else {
                triggerWorklogDialog();
                trackLogWorkWithShortcut();
            }
        }
    }

    function isTempoAppPage() {
        var appWrappers = ['#tempo-issue-app'];
        var arrayLength = appWrappers.length;
        for (var i = 0; i < arrayLength; i++) {
            if ($(appWrappers[i]).length > 0) {
                return true;
            }
        }
        return false;
    }

    function triggerGlobalWorklogDialog(data) {
        var tempoDialogDiv = document.getElementById('tempo-global-dialog-holder');
        if (!tempoDialogDiv) {
            tempoDialogDiv = document.createElement('div');
            $(tempoDialogDiv).attr('id', 'tempo-global-dialog-holder')
                .css({
                    'left': '0',
                    'height': '100%',
                    'width': '100%',
                    'position': 'absolute',
                    'top': '0',
                    'background': 'transparent',
                    'z-index': 9000
                });
            document.body.appendChild(tempoDialogDiv);
        }
        var wlDialog = $(tempoDialogDiv).tempoFrame({
            loadUrl: contextPath() + '/secure/GlobalWorklogDialog.jspa?decorator=none',
            onContentLoaded: function ($container) {
                $container.hideSpinner();
            },
            onStart: function ($container) {
                $('html').css({'overflow': 'hidden'});
                $container.css({top: window.pageYOffset});
                $container.showSpinner();
            },
            onClose: function () {
                $('html').css({'overflow': 'auto'});
            },
            initialData: data
        });
        window.document.addEventListener('tempo-worklog-created', function () {
            AJS.trigger('worklogsChanged');
        }, false);
        window.document.addEventListener('tempo-worklog-dialog-opened', function () {
            AJS.trigger('logWorkOpened');
        }, false);
        window.document.addEventListener('tempo-open-worklog-dialog-close', function () {
            wlDialog.close();
        }, false);
    }

    /*
    * PM-158: New issue view and update TUI worklog form for p2
    * The event is binded at src/io/frontend/js/utils/connect-utilities.p2.js#registerOpenWorklogDialog
    */
    function triggerWorklogDialog(customData) {
        var data = customData || {};
        if (isTempoAppPage()) {
            AJS.trigger('tempo-open-worklog-dialog-bundled', data);
        } else {
            triggerGlobalWorklogDialog(data);
        }
    }

    return {
        shortcutOpenDialog: shortcutOpenDialog,
        triggerWorklogDialog: triggerWorklogDialog,
        triggerGlobalWorklogDialog: triggerGlobalWorklogDialog
    }
});

}catch(e){WRMCB(e)};
;
try {
/* module-key = 'is.origo.jira.tempo-plugin:tempo-global', location = 'lib/tempoSpinner.js' */
define('tempo-spinner', ['jquery'], function($) {
    return $('<div class="tempo-iframe-page-spinner-container">' +
        '<svg\n' +
        '        class="tempo-toast-img tempo-iframe-page-spinner"\n' +
        '        version="1.1"\n' +
        '        id="outerRingContainer"\n' +
        '        xmlns="http://www.w3.org/2000/svg"\n' +
        '        x="0px"\n' +
        '        y="0px"\n' +
        '        width="250px"\n' +
        '        height="250px"\n' +
        '        viewBox="0 0 125 125"\n' +
        '>\n' +
        '    <g id="outerRingPath">\n' +
        '        <g id="outerRingGroup">\n' +
        '            <path\n' +
        '                    fill="#ccc"\n' +
        '                    id="outerRing"\n' +
        '                    class="tempo-iframe-spinner-outer-ring"\n' +
        '                    d="M112.3,74.7c-6.1,24.8-29.6,41.4-55,38.8l8.9,8.9c30.9-1.9,\n' +
        '                    55.3-27,56.3-57.9L112.3,74.7z M113.8,62.5c0,1.8-0.1,3.5-0.3,\n' +
        '                    5.2l8.9-8.9c-1.9-30.9-27-55.3-58-56.3l10.2,10.2C97.6,18.3,113.8,\n' +
        '                    38.8,113.8,62.5z M62.5,11.2c1.7,0,3.3,0.1,4.9,0.2l-8.9-8.9c-30.8,\n' +
        '                    2-55.1,27.1-56,58l10.2-10.2C18.3,27.4,38.9,11.3,62.5,11.2z M11.2,\n' +
        '                    62.5c0-1.7,0.1-3.3,0.2-4.9l-8.9,8.9c2,30.8,27.1,55.1,58,\n' +
        '                    56.1l-10.2-10.2C27.4,106.7,11.3,86.1,11.2,62.5z"\n' +
        '            />\n' +
        '        </g>\n' +
        '    </g>\n' +
        '    <path\n' +
        '            fill="#ccc"\n' +
        '            id="innerRingPath"\n' +
        '            d="M62.5,19.7c-23.6,0-42.8,19.1-42.8,42.8s19.1,42.8,42.8,42.8s42.8-19.1,\n' +
        '            42.8-42.8S86.1,19.7,62.5,19.7C62.5,19.7,62.5,19.7,62.5,19.7z M62.5,\n' +
        '            96.6c-18.8,0-34.1-15.3-34.1-34.1s15.3-34.1,34.1-34.1s34.1,15.3,34.1,\n' +
        '            34.1S81.3,96.6,62.5,96.6z"\n' +
        '    />\n' +
        '    <g id="tempoLogoGroup">\n' +
        '        <path\n' +
        '                fill="#ccc"\n' +
        '                id="tempoLogoPath"\n' +
        '                class="tempo-iframe-spinner-logo"\n' +
        '                d="M85,52.3l-7.9-7.9c-0.6-0.6-1.5-0.6-2,0L58.7,60.8c-0.6,0.6-1.5,\n' +
        '                0.6-2,0c0,0,0,0,0,0L49.8,54c-0.6-0.6-1.5-0.6-2,0L40,61.8c-0.6,\n' +
        '                0.6-0.6,1.5,0,2l16.7,16.7c0.6,0.6,1.5,0.6,2,0L85,54.4C85.6,53.8,\n' +
        '                85.6,52.9,85,52.3C85,52.3,85,52.3,85,52.3z"\n' +
        '        />\n' +
        '    </g>\n' +
        '</svg>' +
        '</div>');
});
}catch(e){WRMCB(e)};
;
try {
/* module-key = 'is.origo.jira.tempo-plugin:tempo-global', location = 'lib/jquery.tempo.iframe.js' */
/*===================================================================================================================
 * options: {
 *  loadUrl: String.isRequired (src url for iFrame)
 *  iframeAttr: String (element attributes for iFrame)
 *  appendTo: String (where to append iFrame container)
 *  onStart: func (callback once container is shown)
 *  onContentLoaded: func (callback once iframe is loaded)
 * }
 *==================================================================================================================*/
require(['jquery', 'tempo-spinner'], function ($, spinner) {
    'use strict';
    $.fn.tempoFrame = function (options) {

        // OPTIONS
        var o = $.extend({}, $.fn.tempoFrame.defaults, options);

        // VARIABLES
        var $frameContainer = this;
        var $iframe = $('<iframe class="tempo-iframe" ' + o.iframeAttr + '></iframe>');

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // PUBLIC FUNCTION - call it: $(iframeContainerElement).tempoFrame().close();
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        $frameContainer.close = function () {
            close();
        };

        $frameContainer.hideSpinner = function () {
            $('.tempo-iframe-page-spinner-container').hide();
        };

        $frameContainer.showSpinner = function () {
            $('.tempo-iframe-page-spinner-container').show();
        };

        init();
        return $frameContainer;

        function init() {
            if (!$('.tempo-iframe-page-spinner-container').length) {
                $frameContainer.append(spinner);
            }

            if (!o.loadUrl) {
                console.error('Error: No loadUrl defined')
            }
            $frameContainer.children('iframe').remove();
            $iframe.hide();  // Need to hide until content is loaded cause of IE11
            $iframe.appendTo($frameContainer);
            $iframe.attr('src', o.loadUrl);
            $iframe.attr('data-initial-data', JSON.stringify(o.initialData));
            $iframe.on('load', function() {
                o.onContentLoaded($frameContainer);
                $iframe.show();
            });
            open();
        }

        function open() {
            $frameContainer.each(function () {
                $(this).appendTo(o.appendTo);
            });
            $frameContainer.show();
            o.onStart($frameContainer);

        }

        function close() {
            $frameContainer.hide();
            $iframe.remove();
            o.onClose($frameContainer);
            return false; // Prevent default
        }
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // DEFAULT VALUES
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    $.fn.tempoFrame.defaults = {
        appendTo: 'body',
        iframeAttr: 'scrolling="no" frameborder="0" style="width: 100%; height: 100%; background: transparent;"',
        onContentLoaded: function() {},
        onStart: function() {},
        onClose: function() {}
    };
});

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