var e_width = 71;
var e_height = 72;
var is_clicked = false;
var _length = parseInt(elements.length);
var resized = true;
var timeout = 1;
var ids = [];
var used_ids = [];
var current_num;
var timeout_id;

Array.prototype.inArray = function(val) {
    for (var i in this)     {
        if (this[i] === val) return true;
    }

    return false;
}

function createMatrix() {
    $('.mosaic').css('height', $('.container').height() - $('.fw').height() + 'px');

    $('.elements').html('').hide();
    var w = $('.mosaic').width();
    var h = $('.mosaic').height();

    var sum_h = css_top = 0;
    row = Math.ceil(h / e_height);

    var fh = $('.container').height()-(row-1)*e_height;
    $('.fw').css({marginTop: parseInt((fh-$('.fw').height())/2)+'px'});
    $('.footer').css({height: (fh)+'px'});
    $('.container').css({marginBottom: '-'+(fh)+'px'});
    $('.push').css({height: (fh)+'px'});

    while (sum_h < h - e_height) {
        var sum_w = css_left = col = 0;
        while (sum_w < w - e_width) {
            $('.elements').append('<div class="mosaic_element" style="left:'+css_left+'px;top:'+css_top+'px;z-index:'+(row + col)+'" id="'+(css_left.toString() + css_top.toString())+'"></div>');
            sum_w += e_width;
            css_left += e_width;
            col++;
        }

        row--;
        css_top += e_height;
        sum_h += e_height;
    }

    ids = [];

    $('.mosaic_element').each(function () {
        ids.push(this.id);
        $(this)
            .attr('rnd', -1)
            .click(function () {
                if (!is_clicked) {
                    _clearTimeout();
                    setTimeout(chain_click, timeout);
                    current_num = $(this).attr('rnd');
                } else {
                    fillMatrix();
                }

                is_clicked = !is_clicked;
            })
            .mouseover(function () {
                $(this).unbind('mousemove');
                $(this).mousemove(function (e) {
                    $('.bubble').css({top: (e.clientY-100)+'px', left: (e.clientX-35)+'px'});
                });

                if (!is_clicked) {
                    $('.bubble').find('p').html(elements[$(this).attr('rnd')].title);
                } else {
                    $('.bubble').find('p').html(elements[current_num].alts[$(this).attr('rnd_a')]);
                }

                $('.bubble').show();
            })
            .mouseout(function () {
                $('.bubble').hide();
            });
    });

    if (resized) {
        $('.mosaic').css('left', '0px');
        var total_width = parseInt($('.mosaic_element:last').css('left')) + e_width + 3;
        $('.mosaic').css('left', ($('.container').width() - total_width) / 2);
    }
}

function fillMatrix() {
    _clearTimeout();

    $('.mosaic_element').each(function () {
        $(this).attr('rnd', $.random(_length))
    });

    timeout_id = setTimeout(chain_show, timeout);
    $('.elements').show();
}

function chain_show() {
    if (used_ids.length < ids.length) {
        i = get_random_index();
        $o = $('#' + ids[i]);
        $o.css('background-image', 'url(' + elements[$o.attr('rnd')].image + ')');
        timeout_id = setTimeout(chain_show, timeout);
    } else {
        used_ids = [];
    }
}

function chain_click() {
    if (used_ids.length < ids.length) {
        $o = $('#' + ids[get_random_index()]);
        $o.css('background-image', 'url(' + elements[current_num].image + ')');
        $o.attr('rnd_a', $.random(parseInt(elements[current_num].alts.length)));
        timeout_id = setTimeout(chain_click, timeout);
    } else {
        used_ids = [];
    }
}

function get_random_index() {
    do {
        index = $.random(ids.length);
    } while (used_ids.inArray(index))

    used_ids.push(index);

    return index;
}

function _clearTimeout() {
    clearTimeout(timeout_id);
    used_ids = [];
}

$(document).ready(function () {
    createMatrix();
    fillMatrix();
    $('<p>').appendTo($('<div>').addClass('bubble').appendTo($('body')));
});

$(window).resize(function () {
    createMatrix();
    fillMatrix();
    resized = true;
});
