Event.observe(window, 'load',function(){setTimeout(init, 3000)});


function init(){
    if(document.all && !window.opera)
        return;

    var posts = $X('descendant-or-self::*[contains(concat(" ",@class," "), " photo ")]');
    var dx = 1;
    posts.forEach(function(e){
        var img = $X('descendant::img[1]', e)[0];
        activate_ami(e, img);
        var r = document.createElement('canvas');
        if (r.getContext) {
            var context = r.getContext("2d");
            r.style.width = img.clientWidth + 'px';
            r.style.height = img.clientHeight + 'px';
            r.width = img.clientWidth;
            r.height = img.clientHeight;

            for(var x = 2; x < img.clientWidth-2 ; x += dx * 2){
                context.drawImage(
                    img, x, 0, dx, img.clientHeight - 2,
                    x, 0, dx, img.clientHeight - 2
                );
                context.drawImage(
                    img, (img.clientWidth - x - dx), 0, dx, img.clientHeight - 2,
                    x + dx, 0, dx, img.clientHeight - 2
                );
            }

            context.restore();
        }
        img.parentNode.appendChild(r);
        img.parentNode.removeChild(img);
    });
}

function activate_ami(wrapper, img){
    var width = img.clientWidth;
    var height = img.clientHeight;
    var box = $X('descendant-or-self::div[@class="ami_box"]',wrapper)[0];
    var ami = $X('descendant-or-self::div[@class="ami"]',wrapper)[0];
    box.style.width = width + 15 + 'px';
    box.style.height = height + 15 + 'px';
    ami.style.height = height + 'px';
    setInterval(
        function(){
            var dx = 1;
            var max = width;
            return function(){
                dx = ((width - 4) <= box.scrollLeft || 0 >= box.scrollLeft) ? -dx : dx;
                box.scrollLeft = box.scrollLeft += dx;
            }
        }(),
        150
    );
}

// simple version of $X
// $X(exp);
// $X(exp, context);
// @source http://gist.github.com/3242.txt
function $X (exp, context) {
    context || (context = document);
    var expr = (context.ownerDocument || context).createExpression(exp, function (prefix) {
        return document.createNSResolver(context.documentElement || context).lookupNamespaceURI(prefix) ||
            context.namespaceURI || document.documentElement.namespaceURI || "";
    });

    var result = expr.evaluate(context, XPathResult.ANY_TYPE, null);
    switch (result.resultType) {
    case XPathResult.STRING_TYPE : return result.stringValue;
    case XPathResult.NUMBER_TYPE : return result.numberValue;
    case XPathResult.BOOLEAN_TYPE: return result.booleanValue;
    case XPathResult.UNORDERED_NODE_ITERATOR_TYPE:
        // not ensure the order.
        var ret = [], i = null;
        while (i = result.iterateNext()) ret.push(i);
        return ret;
    }
    return null;
}
