$(document).ready(function(){
    if ($('#url_shortener')[0] != undefined){
        var target = $('#url_shortener'), val = target.val;

        $('#result').click(function(){
            SelectText('result');
        });
        $('#lightbox-image-details-caption').click(function(){
            SelectText('result');
        });
        $(".quote").click(function(){
            var link = $(this).data("path");
            $("#body").val($("#body").val() + link);
        });

        target.keyup(monitor);
    
//    document.getElementById("result").onclick = select();
//    $('.result').click($(this).select());
        function monitor() {
            var current_val = $(this).val();
            if (current_val != val) {
                sendUrlToBitly(current_val, 'result');
                val = current_val;
            }
        }
    }
});

function sendUrlToBitly(url, element){
    
    $.getJSON("http://api.bitly.com/v3/shorten?login=operalabb&apiKey=R_d4c759d5effe32fef4e9fda685db52b9&longUrl="+encodeURI(url)+"&format=json", function(response){
        if(response == null){
            console.log("getAllMessages returned null");
        }
        $('#'+element).html(response.data.url);
    });
}

function SelectText(element) {
    var text = document.getElementById(element);
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}
