(function(stream, base, common, undefined) {
    var updated;
    var earliest, latest;
    var wait = 3;
    
    stream.init = function(amount, continuation) {
        api(common.format("{0}?limit={1}", base, amount || 60), function() {
            if (typeof continuation == "function")
                continuation();
            delete(stream.init);
        });
    };
    
    stream.prev = function(count) {
        if (!earliest)
            stream.init();
        else
            api(common.format("{0}?limit={1}&before={2}", base, count, earliest));
    };
    
    stream.next = function(count) {
        if (!latest)
            stream.init();
        else
            api(common.format("{0}?limit={1}&after={2}", base, count, latest));   
    };
    
    stream.callback = function (item) { };

    stream.items = {};

    function api(url, continuation) {
        if (!url || (common.time() - updated) < wait)
            return;
        updated = common.time();
        
        var request = window.XMLHttpRequest ? 
            new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");   
        request.onreadystatechange = function() {
            if (request.readyState == 4)
                if (json = decode(request.responseText))
                    callback.apply(this, [json, continuation]);
        };
        request.open('GET', url, true);
        request.send();
    }

    function decode(json) {
        if (/^[\],:{}\s]+$/.test(
        	json.replace(/\\["\\\/bfnrt]|\\u[0-9a-fA-F]{4}/g, "$")
        	    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
        		.replace(/(?:^|:|,)(?:\s*\[)+/g, ""))) {
            return stream.$eval("("+json+")");
        }
    }
    
    function callback(items, continuation) {
        if (typeof continuation == "function") 
            continuation.apply(this);
        items.map(function(item) {
            stream.items[item.guid] = item;
            if (!earliest || item.date < earliest)
                earliest = item.date;
            if (!latest || item.date > latest)
                latest = item.date;
            if (stream.callback)
                stream.callback(item);
        });
    } 
})(window.stream = window.stream || {}, './stream/get.json', window.common);

stream.$eval = function(s) {
    return eval(s);
};	


