String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
}

/**
 * This is the common js code for insert link and image popups in both the wiki markup and wysiwyg editors.
 *
 * AJS.Popup.delegate should be set to a popup-specific object implementing submit, validate and init methods.
 */
AJS.Popup = {
    // TODO - remove this method, use AJS.Editor.Markup.insertOrUpdateText
    // Inserts text into the text area specified (currently compatible with Netscape, mozilla, ie)
    // Note: for IE compatibility, storeCaret(this) must be called in the onclick, onselect and onkeyup events
    // of the text area object specified
    insertOrUpdateText: function (text, textAreaObject) {
        if (window.getSelection && textAreaObject.selectionStart && textAreaObject.selectionStart != null) {
            textAreaObject.value = textAreaObject.sel1 + text + textAreaObject.sel2;
            textAreaObject.focus();
            textAreaObject.selectionStart = textAreaObject.selectionEnd = textAreaObject.sel1.length + text.length;
        } else if (textAreaObject.createTextRange && textAreaObject.caretPos) {
            // for IE
            // IE supports createTextRange(), test for non-null caretPos (if its been set)
            var caretPos = textAreaObject.caretPos;
            caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text + ' ' : text;
        } else {
            // for ie users that don't set the caret OR
            // for other browsers
            // just append link at the end of the current text inside the text area
            textAreaObject.value += text;
        }
    },

    // default delegate.
    delegate: {
        init: function() { },
        submit: function() { },
        validate: function() { return true; }
    },

    submit: function() {
        if (!AJS.Popup.delegate.validate())
            return false;

        AJS.Popup.delegate.submit();
        window.close();
    },

    cancel: function() {
        window.close();
    },

    validate: function() {
        this.delegate.validate();
    },

    init: function() {
        AJS.$("#popup-errorBox li").hide();

        this.delegate.init();
    }
};

