///////////////////////////////
//Label Specific Functionality
///////////////////////////////

YAHOO.namespace("jira.labels");
function showEditLabelsPanel(issueId, customFieldId, response)
{
    //if (!YAHOO.jira.labels.panel) {
    YAHOO.jira.labels.panel = new YAHOO.widget.Panel("YAHOO.jira.labels.panel", {
        effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.15},
        width:"700px",
        height:"20em",
        fixedcenter: false,
        constraintoviewport: true,
        underlay:"none",
        close:false,
        visible:false,
        draggable:false,
        modal:true
    });

    var esc_key = new YAHOO.util.KeyListener(
        document,
        { keys:27 },
        {
            fn:YAHOO.jira.labels.panel.destroy,
            scope:YAHOO.jira.labels.panel,
            correctScope:true
        }
    );

    var return_key = new YAHOO.util.KeyListener(
        document,
        { keys:13 },
        {
            fn:function()
            {
                addLabel(issueId, customFieldId, $('labelName_' + issueId).value);
                return false;
            },
            scope:YAHOO.jira.labels.panel,
            correctScope:true
        }
    );

    YAHOO.jira.labels.panel.cfg.queueProperty("keylisteners", [esc_key, return_key]);
    YAHOO.jira.labels.panel.render(document.body);
;
    YAHOO.jira.labels.panel.setBody(response.responseText);
    YAHOO.jira.labels.panel.render();
    
    var yuiConfig = {
            minQueryLength : 1,
            queryDelay : 0.25,
            cacheResults : false,
            maxResultsDisplayed : 10,
            delimChar : [' ']
    }

    var config = {
        inputId : "labelName_" + issueId,
        containerId : "labelContainer_" + issueId,
        resultsId : "labelsAutocompleteList_" + issueId,
        waiticonId : "labelsWaiticon_" + issueId,
        dwrInvokerFunc : function(query, dwrCallContext)
        {
            AjaxHelper.getSuggestedLabels(issueId, query, customFieldId, dwrCallContext);
        }
    };
    YAHOO.jira.labels.autocomplete = new atlassian.jira.widget.AutoComplete(config, yuiConfig);

    YAHOO.jira.labels.panel.show();
    YAHOO.jira.labels.panel.center();
    $('labelName_' + issueId).focus();
}

function closeEditLabelsPanel(issueId, customFieldId)
{
    if ($('labelName_' + issueId).value)
    {
        addLabel(issueId, customFieldId, $('labelName_' + issueId).value, function () { YAHOO.jira.labels.panel.destroy(); });
    }
    else
    {
        YAHOO.jira.labels.panel.destroy();
    }
}

function showLabels(baseUrl, issueId, customFieldKey, successCallback)
{
    var uri = baseUrl + '/com.atlassian.jira.plugin.labels.action.EditIssueLabels.jspa?issueId=' + issueId + '&customFieldKey=' + customFieldKey;
    var callback = {
        success: function (response) { successCallback(issueId, customFieldKey, response); },
        failure: function(response) {}
    };
    // do ajax call
    YAHOO.util.Connect.asyncRequest('GET', uri, callback, null);
}

function addLabelDuringIssueEdit(customFieldId, label)
{
    var customFieldValue = $(customFieldId).value;
    var prependSpace = customFieldValue.length > 0 && customFieldValue.charAt(customFieldValue.length - 1) != ' ';

    $(customFieldId).value = customFieldValue + (prependSpace ? ' ' : '') + label;
}

function addLabel(issueId, customFieldId, labelsString, callback)
{
    hideErrorMessage(issueId);
    AjaxHelper.addLabel(
        issueId,
        labelsString,
        customFieldId,
        function (data)
        {
            updateLabels(issueId, customFieldId, data);
            if (callback)
            {
                callback();
            }
        }
    );
    $('labelName_' + issueId).value = '';
}

function removeLabel(issueId, customFieldId, label)
{
    hideErrorMessage(issueId);
    AjaxHelper.removeLabel(issueId, label, customFieldId, function(response)
    {
        updateLabels(issueId, customFieldId, response);
    });
}

function updateLabels(issueId, customFieldId, data)
{
    var response = data.response;
    if (data.success)
    {
        DWRPluginUtil.setValue('labels_' + issueId, DWRPluginUtil.toDescriptiveString(response, 1));
        response = response.replace(/<span class="delLabelImage">/g, "");
        response = response.replace(/<\/span>/g, "");
        response = response.replace(/<a onClick="removeLabel.*>/g, "")
        response = response.replace(/<\/a>/g, "</a>")
        response = response.replace(/^\s+|\s+$/g, '');
        DWRPluginUtil.setValue('no-link-list_' + issueId + '_' + customFieldId, DWRPluginUtil.toDescriptiveString(response, 1));
    }
    else
    {
        showErrorMessage(issueId, DWRPluginUtil.toDescriptiveString(response, 1));
    }
}

function showErrorMessage(issueId, message)
{
    document.getElementById('labelErrorMessage_' + issueId).innerHTML = message;
    document.getElementById("labelErrorContainer_" + issueId).style.display = 'block';
}

function hideErrorMessage(issueId)
{
    if (document.getElementById("labelErrorContainer_" + issueId).style.display != null)
    {
        document.getElementById('labelErrorMessage_' + issueId).innerHTML = '';
        document.getElementById("labelErrorContainer_" + issueId).style.display = 'none';
    }
}

// ':', ';', ',', '.', ' ', '?', '&', '[', ']', '(', ')', '#', '^', '*', '@', '!', '<', '>', '\''
function checkInput(issueId)
{
    var value = $(issueId).value;
    if (value.match(/[\:\;\,\.\?\&\[\]\(\)\#\^\*\@\!\<\>\\]/))
    {
        showErrorMessage(issueId, "Tags cannot contain: ':', ';', ',', '.', ' ', '?', '&', '[', ']', '(', ')', '#', '^', '*', '@', '!', '<', '>', '\'");
    }
    else
    {
        hideErrorMessage(issueId);
    }
}
