ExtensionPreprocessingJS = {

    run: function(arguments) {
        var sdata = ExtensionPreprocessingJS.getSelectionData();
        arguments.completionFunction({"url" : document.baseURI,
                                     "title":document.title,
                                     "selectedContent": sdata.text,
                                     "selectedImages": sdata.images});
    },
    
    getSelectionData: function() {
        var html = "";
        var text = "";
        if (typeof window.getSelection != "undefined") {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var container = document.createElement("div");
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
                text = container.innerText;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().innerHTML;
                text = document.selection.createRange().innerText;
            }
        }
        
        text = text.replace(/\t/g, "");
        text = text.replace(/^\s+/g, "");
        text = text.replace(/\s+$/g, "");
        text = text.replace(/\n\s*\n\s*\n+/g, "\n\n");
        
        if(text.length > 512) {
            text = text.substring(0, 511) + "...";
        }
        
        return {"text": text, "images": ExtensionPreprocessingJS.getImages(html)};
    },
    
    getImages: function(html) {
        var images = [];
        var matches = html.match(ExtensionPreprocessingJS.reg_exp);
        
        if (matches == null)
            return images;
        
        for(var j=0; j < matches.length; j++) {
            var match = matches[j].match(/src=["']([^'"]+)/i)[1];
            images.push(match);
            if(images.length > 2) {
                break;
            }
        }
        return images;
    },
    
    reg_exp: /<img[^>]+src=["']([^'"]+)[^>]+["']>/gi
    
}