$(document).ready(function() {
    set_position($('.illustration.visible'));
    //set_position($('.illustration.visible'));
});

$(window).bind('resize', function() {

    $('.illustration').each(function(){
        if ($(this).hasClass("visible")) {
            set_position($(this));
        }
    
    });

});

$('a.illustrated-link').live('mouseover', function(){

    show_illustration(this);

});

function arr_remove(a, item){
    var res = new Array();
    for (var i = 0; i < a.length; i++)
    {
      if (a[i] != item) {
          res.push(a[i]);
      }
    }

    return res;
}

function set_position(item) {

    var width = $(window).width();
    //alert(width);
    var div_width = item.width();
    //alert(div_width);
    var offset = (width - div_width) / 2;
    //alert(offset);
    item.css({
        position: 'absolute',
        top: '0px',
        left: offset + 'px'
    });

}

function pick_illustration(rel) {
    var current = $(".illustration.visible").attr("id");
    var choices = rel.split(" ");
    if (choices.length > 1) {
        choices = arr_remove(choices, current);
    }
    if (choices.length > 1) { //if it's still >1 after filtering'
        var choice = Math.floor(Math.random() * choices.length);
        return choices[choice];
    } else {
        return choices[0];
    }

    
}

function show_illustration($this) {

    //var already_visible = $($this).hasClass('visible');
    var rel = $($this).attr("rel");
    var choice = pick_illustration(rel);
    //alert(choice);
    var el = $('#' + choice);
    //alert(el.html());
    var vis = el.hasClass('visible');
    //alert(vis);

    if (!vis) {
            $('.illustration').each(function(){

            var obj = $(this);

            if (obj.hasClass("visible")) {

                if (rel != obj.attr("id")) {
                    obj.removeClass("visible");
                }

            }
        });
        set_position(el);
        el.addClass('visible');

    }

}