(function(){
    function getImageSize(imgSrc) {
        var newImg = new Image();
        newImg.src = imgSrc;
        var height = newImg.height;
        var width = newImg.width;
        return { width: width, height: height };
    }
    function getImageData(img) {
        var size = getImageSize(img.src);
        // Create an empty canvas element
        var canvas = document.createElement("canvas");
        canvas.width = size.width;
        canvas.height = size.height;

        // Copy the image contents to the canvas
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        // Get the data-URL formatted image
        // Firefox supports PNG and JPEG. You could check img.src to
        // guess the original format, but be aware the using "image/jpg"
        // will re-encode the image.
        var dataURL = canvas.toDataURL("image/png");

        return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    }
    function saveRemoteImagesToCache(doc) {
        //
        var obj = null;
        try {
            obj = window.external;
        } catch (exp) {
            alert(exp);
            return;
        }
        if (!obj)
            return;
        var images = doc.images;
        for (var i = 0; i < images.length; i++) {
            var img = images[i];
            //
            var src = img.src;
            if (src.indexOf("data:") == 0)
                continue;
            if (0 == src.indexOf("http")) {
                try {
                    var data = getImageData(img);
                    //
                    obj.SetImageData(src, data);
                }
                catch (e) {
                }
            }
        }
    }
    //
    saveRemoteImagesToCache(document);
})();

