// Insert documentAction icon for URL shortening service:
jq(function() {
    function shorten(callback) {
        jq.ajax({
            'url': 'http://uni-marburg.de/shorten/' + encodeURIComponent(location.href),
            'dataType': 'jsonp',
            'success': function(data) {
                callback('<p style="font-size:10px">Ihre Kurz-URL lautet:</p><p><a href="' + data.url + '" target="_blank">' + data.url + '</a></p>');
                },
                'error': function(jqXHR, textStatus, errorThrown) {
                    switch(errorThrown) {
                        case 'Forbidden':
                        case 'Bad Request':
                        case 'Not Implemented':
                        case 'Invalid URL':
                            var result = '<p>Die von Ihnen eingegebene Web-Adresse ist fehlerhaft und kann nicht gekürzt werden.</p>';
                            break;
                        case 'Target URL Too Short':
                            var result = '<p>Die von Ihnen angegebene Web-Adresse kann nicht weiter gekürzt werden.</p>';
                            break;
                        case 'Service Unavailable':
                        case 'Bad gateway':
                            var result = '<p>Der Dienst steht aufgrund eines Fehlers temporär nicht zur Verfügung.</p>';
                            break;
                        default:
                            var result = '<p>Es ist ein Fehler aufgetreten</p>';
                    }
                    callback(result);
                }
        });
    }

    function displayOverlay(content) {
        jq('#document_action_shorten').unbind('click');
        jq('#document_action_shorten').parent().append('<div id="unimr_shorten_overlay"><div id="unimr_shorten_overlay_content">' + content + '<div id="unimr_shorten_overlay_arrow"></div><div id="unimr_shorten_overlay_close"></div></div></div>');
        jq('#unimr_shorten_overlay').css('left', jq('div.documentActions ul:first li').length * 20 - 120 + 'px');
        jq('#unimr_shorten_overlay_close').click(destroyOverlay);
        jq('html').click(destroyOverlay);
        jq('#unimr_shorten_overlay').click(function(event) { event.stopPropagation(); });
    }

    function destroyOverlay() {
        jq('#unimr_shorten_overlay').remove();
        jq('html').unbind('click');
        jq('#document_action_shorten').click(function() { shorten(displayOverlay); });
    }

    if (location.href.length > 27 && location.href.match(/^https?:\/\/www\.uni-marburg\.de/) !== null && location.href.match(/html2pdf_form$/) === null) {
        jq('div.documentActions ul:first').append('<li><img src="/shrtn.gif" alt="Kurz-URL" title="Kurz-URL anfordern" id="document_action_shorten" style="cursor:pointer" /></li>');
        jq('#document_action_shorten').click(function() { shorten(displayOverlay); });           
    }
});

