AJS.Popup.Link = {
    init: function() {
        AJS.$(window).bind("beforeunload", AJS.Popup.Link.save);
        try {
            if (window.opener.AJS.Editor.LinkPopup) {
                AJS.$("#destination").val(window.opener.AJS.Editor.LinkPopup.destination);
                AJS.$("#alias").val(window.opener.AJS.Editor.LinkPopup.alias);
                AJS.$("#tooltip").val(window.opener.AJS.Editor.LinkPopup.tooltip);
            }

            AJS.$(".attachment_link").click(function() {
                var filename = AJS.$(this).text();
                AJS.Popup.Link.populateDestinationLinkField('^'+filename);
            });
        } catch (error) {
            AJS.log(error);
        }
    },

    validate: function() {
        if (!AJS.$("#destination").val()) {
            AJS.$("#popup-errorBox").show().find("#noDestinationLinkError").show();
            return false;
        }
        return true;
    },

    submit: function() {
        var wikiMarkupTextarea = window.opener.document.forms[AJS.params.formname].elements[AJS.params.fieldname];
        AJS.Popup.insertOrUpdateText("[" + this.getWikiMarkup() + "]", wikiMarkupTextarea);
    },

    getWikiMarkup: function() {
        var alias = AJS.$("#alias").val();
        var destination = AJS.$("#destination").val();
        var tooltip = AJS.$("#tooltip").val();

        var link = destination;

        if (tooltip && !alias) { // can't have tooltip without an alias in wiki markup
            alias = destination;
        }

        if (tooltip) {
            link = alias + '|' + destination + '|' + tooltip;
        }
        else if (alias) {
            link = alias + '|' + destination;
        }
        return link;
    },

    populateDestinationLinkField: function (link) {
        AJS.$("#destination").val(link);
        return false;
    },

    save: function() {
        try {
            if (window.opener.AJS.Editor.LinkPopup) {
                window.opener.AJS.Editor.LinkPopup.destination = AJS.$("#destination").val();
                window.opener.AJS.Editor.LinkPopup.alias = AJS.$("#alias").val();
                window.opener.AJS.Editor.LinkPopup.tooltip = AJS.$("#tooltip").val();
            }
        } catch (error) {
            AJS.log(error);
        }
    }
};

AJS.toInit(function($) {    
    AJS.Popup.delegate = AJS.Popup.Link;
    AJS.Popup.init();
});
// if you like, you can try cleaning this up...
populateDestinationLinkField = AJS.Popup.Link.populateDestinationLinkField;