jQuery(function ($) {

    var opt = {
        url: 'http://higan.net/', // サイトのURL
        time: 'w', // h：最近1時間, d：最近24時間, w：最近一週間, m：最近1ヶ月間, a：全期間
        count: 5, // いくつまで表示するか (デフォルト10, 最大50)
        del: '', // 取得したエントリータイトルから削除したい文字列
        showcount: true // ○○tweets を表示するかどうか (true/false デフォルトtrue)
    }

    // パラメータ用に整形
    var param = {
        url: opt.url.replace(/^http(|s):\/\/|\/$/g, ''),
        time: (opt.time != null && opt.time.match(/^[hdwma]{1}$/)) ? opt.time : 'auto',
        cnt: (opt.count > 0 && opt.count < 51) ? opt.count : 10
    }

    // コールバック関数
    function twiRank(data) {
        var list = '';

        // 1つもなければ終了
        if (data.response.total === 0) return;

        // レスポンスの配列数だけループさせる
        for (i = 0; i < data.response.list.length; i++) {

        // tweet数(Topsyへのリンク付き)
            if (opt.showcount !== false) {
                tweets = (data.response.list[i].trackback_total > 1) ? 'tweets】' : 'tweet】';
                list += '<li><a href="' + data.response.list[i].topsy_trackback_url + '" target="_blank">'
                list += '【' + data.response.list[i].trackback_total + tweets;
                list += '</a>';
            }
            // エントリーへのリンク
            list += '<a href="' + data.response.list[i].url + '">';

            // エントリーのタイトル (消したい文字列がない場合はそのまま)
            if (opt.del !== '') {
                list += data.response.list[i].title.replace(opt.del, '');
            } else {
                list += data.response.list[i].title;
            }

            list += '</a>'
            list += '</li>';
        }

        // 指定した ID 内にol要素を作ってリストを追加
        $('#twirank').html('<ol>' + list + '</ol>');

    }

    // JSONPを取得
    $.getJSON('http://otter.topsy.com/search.js?q=site%3A' + param.url + '&window=' + param.time + '&perpage=' + param.cnt + '&callback=?', twiRank);

});

