(function() {
	window.FANFOU = {};
    var userAgent = (function() {
        var b = navigator.userAgent.toLowerCase();
        return {
            safari: /webkit/.test(b),
            opera: /opera/.test(b),
            msie: /msie/.test(b) && !(/opera/).test(b),
            mozilla: /mozilla/.test(b) && !(/(compatible|webkit)/).test(b)
        };
    })();
    var counter = 0; // 计数
	var apiUrl = 'http://api.fanfou.com/';
	var siteUrl = 'http://fanfou.com/';
    var funcs = []; 
    var isReady = false; 
	function $(el){
		if(typeof el=='string') { return document.getElementById(el); }
		else if(typeof el=='object') { return el; }
	}
    function render(datas, config) {
        function node(e) { return document.createElement(e); }
        function text(t) { return document.createTextNode(t); }
        var el = $(config.target);
        var data = null;
        var ul = node('ul'), li, statusSpan, timeSpan, i, max = datas.length > config.count ? config.count: datas.length;
        for (i = 0; i < max && datas[i]; i++) {
            data = getData(datas[i]);
            if (config.ignoreReplies && datas[i].text.substr(0, 1) == '@') {
                max++;
                continue;
            }
            li = node('li');
            if (config.template) {
                li.innerHTML = config.template.replace(/%([a-z_\-\.]*)%/ig,
                function(m, l) {
                    var r = data[l] + "" || "";
                    if (l == 'text' && config.enableLinks) r = linkify(r);
                    return r;
                });
            } else {
                statusSpan = node('span');
                statusSpan.className = 'fanfou-status';
                timeSpan = node('span');
                timeSpan.className = 'fanfou-time';
                statusSpan.innerHTML = datas[i].text;
                if (config.enableLinks) {
                    statusSpan.innerHTML = linkify(statusSpan.innerHTML);
                }
                timeSpan.innerHTML = relative_time(datas[i].created_at).link(siteUrl+'statuses/'+data.id);
                if (config.prefix) {
                    var s = node('span');
                    s.className = 'fanfou-prefix';
                    s.innerHTML = config.prefix.replace(/%(.*?)%/g,
                    function(m, l) {
                        return datas[i].user[l];
                    });
                    li.appendChild(s);
                    li.appendChild(text(' '));
                }
                li.appendChild(statusSpan);
                li.appendChild(text(' '));
                li.appendChild(timeSpan);
            }
            ul.appendChild(li);
        }
		li = node('li');
		li.innerHTML = '更多'.link(siteUrl+config.id);
		ul.appendChild(li);
        if (config.clearContents) {
            while (el.firstChild) {
                el.removeChild(el.firstChild);
            }
        }
        el.appendChild(ul);
    }
	/**
	 * @param {HTMLElement} e 内容容器
	 * @param {object} 配置项
	 */
    FANFOU.load = function(e, f, g, h) {
        counter++;
        if (typeof f == 'object') {
            h = f;
            f = h.id;
            g = h.count;
        }
        if (!g) g = 1;
        if (h) {
            h.count = g;
        } else {
            h = {};
        }
        if (!h.timeout && typeof h.onTimeout == 'function') {
            h.timeout = 10;
        }
        if (typeof h.clearContents == 'undefined') {
            h.clearContents = true;
        }
        if (h.withFriends) h.withFriends = false;
        h['target'] = e;
        if (typeof h.enableLinks == 'undefined') h.enableLinks = true;
        window['fanfouCallback' + counter] = function(o) {
            if (h.timeout) {
                clearTimeout(window['fanfouTimeout' + counter]);
            }
            render(o, h);
        };
        ready((function(config, id) {
            return function() {
                if (!$(config.target)) { return; }
				// f是用户id
                var url = apiUrl+'statuses/' + (config.withFriends ? 'friends_timeline': 'user_timeline') + '.json?id='+f+'&callback=fanfouCallback' + id + '&count=20';
                if (config.timeout) {
                    window['fanfouTimeout' + id] = setTimeout(function() {
                        if (config.onTimeoutCancel) window['fanfouCallback' + id] = function() {};
                        config.onTimeout.call($(config.target));
                    }, config.timeout * 1000);
                }
                var script = document.createElement('script');
                script.setAttribute('src', url);
                document.getElementsByTagName('head')[0].appendChild(script);
            };
        })(h, counter));
    };
    DOMReady();

    function getData(a) {
        var b = a, i;
        for (i in a.user) {
            b['user_' + i] = a.user[i];
        }
        b.time = relative_time(a.created_at);
        return b;
    }
	// 注册DOMReady的事件处理函数
    function ready(func) {
        if (!isReady) {
            funcs.push(func);
        } else {
            func.call();
        }
    }
    function fireReady() {
        isReady = true;
        var func = funcs.shift();
        while(func){ 
			func.call(); 
			func = funcs.shift();
		}
    }
    function DOMReady() {
        if (userAgent.mozilla || userAgent.opera) {
            document.addEventListener("DOMContentLoaded", fireReady, false);
        } else if (userAgent.msie) {
            document.write("<scr" + "ipt id=__fanfou_ie_init defer=true src=//:><\/script>");
            var a = $("__fanfou_ie_init");
            if (a) {
                a.onreadystatechange = function() {
                    if (this.readyState != "complete") return;
                    this.parentNode.removeChild(this);
                    fireReady.call();
                };
            }
            a = null;
        } else if (userAgent.safari) {
            var b = setInterval(function() {
                if (document.readyState == "loaded" || document.readyState == "complete") {
                    clearInterval(b);
                    b = null;
                    fireReady.call();
                }
            }, 10);
        }
    }
    function relative_time(a) {
        var b = a.split(" ");
        a = b[1] + " " + b[2] + ", " + b[5] + " " + b[3];
        var c = Date.parse(a);
        var d = (arguments.length > 1) ? arguments[1] : new Date();
        var e = parseInt((d.getTime() - c) / 1000, 10);
        e = e + (d.getTimezoneOffset() * 60);
        var r = '';
        if (e < 60) {
            r = '少于 1 分钟';
        } else if (e < 120) {
            r = '1 分钟前';
        } else if (e < (45 * 60)) {
            r = (parseInt(e / 60, 10)).toString() + ' 分钟前';
        } else if (e < (2 * 90 * 60)) {
            r = '1 小时前';
        } else if (e < (24 * 60 * 60)) {
            r = ' ' + (parseInt(e / 3600, 10)).toString() + ' 小时前';
        } else if (e < (48 * 60 * 60)) {
            r = '1 天前';
        } else {
            r = (parseInt(e / 86400, 10)).toString() + ' 天前';
        }
        return r;
    }
    function linkify(s) {
        return s.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g,
        function(m) {
            return m.link(m);
        });
    }
})();
