/*
 *  Oembed preprocessor, useful as "preview_preprocessor" for WMD.
 *  Replaces links in preview panel text with OEmbed markup.
 */
var get_oembed_processor = function() {
    var oembed_cache = {};

    var update_cache = function(urls, callback) {
        if (urls.length > 0) {
            jQuery.getJSON('/oembed/consume/json/',
                // Using jQuery.param to work around jquery's magic addition of brackets to the variable names.
                // See http://dev.jquery.com/ticket/6057
                jQuery.param({'urls': urls, 'width': 320, 'height': 264, 'template_dir': 'live_preview'}, true),
                function(data) {
                    jQuery.each(urls, function(index, url) {
                        oembed_cache[url] = data[url];
                    });
                    callback();
                }
            );
        }
    };

    var do_preview = function(text, callback) {
        urls = extract_urls(text);

        urls_to_search = [];
        output = text;
        $.each(urls, function(index, url) {
            if (!(url in oembed_cache)) {
                urls_to_search.push(url);
            } else {
                output = do_replace(output, url);
            }
        });
        update_cache(urls_to_search, callback);
        return output;
    };

    var do_replace = function(text, url) {
        oembed = oembed_cache[url];
        if (oembed.oembeds.length > 0) {
            text = text.replace(url, '\n' + oembed.rendered.replace('\n', '', 'g'));
        };
        return text;
    };

    var extract_urls = function(source) {
        URL_RE = RegExp("(http://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_|])", "g");

        output = [];
        while (true) {
            match = URL_RE.exec(source);
            if (match != null) {
                output.push(match[1]);
            } else {
                break;
            }
        }
        return output;
    };

    var oembed_processor = function(text, update_callback){
        return do_preview(text, function() { update_callback(do_preview(text, function() {}))});
    };

    return oembed_processor;
};

