function setlinks(words) {
    var count = 0;
    var text_size = 0;

    var doc;
    if ($('#topicCate1').html()) {
        doc = $('#topicCate1');
    }
    else if ($('#topicCate2').html()) {
        doc = $('#topicCate2');
    }
    else if ($('#topicCate3').html()) {
        doc = $('#topicCate3');
    }
    else if ($('#topicCate4').html()) {
        doc = $('#topicCate4');
    }
    else if ($('#topicCate5').html()) {
        doc = $('#topicCate5');
    }
    else if ($('#topicCate6').html()) {
        doc = $('#topicCate6');
    }
    else if ($('#topicCate7').html()) {
        doc = $('#topicCate7');
    }
    else if ($('#topicCate8').html()) {
        doc = $('#topicCate8');
    }

    if (doc) {
        doc = doc.find('.text');
        replace_doc(doc);
    }

    var res = $('.Res .text');
    for (var i = 0; i < res.size(); i++) {
        if (replace_doc(res.eq(i))) {return;}
    }

    function replace_doc(doc) {

//        alert(doc.html());
        html = doc.html();
        if (! html) {
            return;
        }

        if (text_size > 15000) {
            return;
        }
        text_size += html.length;

        for (var i=0; i<words.length; i++) {
            if (count >= 5) {
                return;
            }

            var replaced = html.replace(words[i], a_tag);
            doc.html(replaced);
        }

	return true;
    }

    function a_tag(str) {
        if (count >= 5) {
            return str;
        }
        tag = '<a href="http://search.ozmall.co.jp/search/?q=';
        tag += encodeURIComponent(str) + '" style="color:blue;">' + str + '</a>';
        count ++;
        return tag;
    }
}

$(document).ready(function() {
    var url = "http://search.ozmall.co.jp/api/autolink/?setlinks=?";
    $.getJSON(url, {}, setlinks);
});


