$(document).ready(function () {

    var nodes = $('.box'), lastNode = nodes[Math.floor(Math.random()*nodes.length)];
    var fadeTime = 4000;

    var setFade = function(object) {
        var choices = $(object).find(".boxgrid");
        var toShow = $(choices[0]).css("opacity") == 0 ? 0 : 1;
        var toHide = toShow > 0 ? 0 : 1;
        $(choices[toShow]).toggleClass('on').css("display", "inline").animate({
            opacity:1
        }, fadeTime);
        $(choices[toHide]).toggleClass('on').animate({
            opacity:0
        }, fadeTime, function(){
            $(this).css("display", "none");
        });
    };

    var pickRandomNode = function() {
        var node = nodes.sort(function() {return 0.5 - Math.random();})[0];
        if ($(node).attr('id') == $(lastNode).attr('id')) {
            return pickRandomNode();
        }
        lastNode = node;
        return node;
    };

    var randomFadeTime = function() {
        return (Math.floor((Math.random()*nodes.length)*1000))+fadeTime;
    };

    var delayRandomFade = function() {
        setTimeout(function() {
            randomFade();
        }, randomFadeTime());
    };

    var randomFade = function() {
        setFade(pickRandomNode());
        delayRandomFade();
    };

    $(".box").each(function() {
        $(this).find(".boxgrid:last").css("opacity", 0).css("display", "none");
        $(this).find(".boxgrid:first").addClass("on");
        $(this).hover(function() {
            if ($(this).css('opacity') == '1') {
                $(this).find(".cover").stop().animate({top:'74px'},{queue:false,duration:160});
            }
        }, function() {
            $(this).find(".cover").stop().animate({top:'114px'},{queue:false,duration:160});
        });
    });

    delayRandomFade();

});