function Apic() { }
Apic.prototype = { weight: '', title: '', description: '', small: '', medium: '', large: '', url: '' };

var ie = /msie/i.test(navigator.userAgent);

function Numsort(a, b) { return a - b; }

function PicGrid(ele, path, width, height, rows, cols, overlay, delay, random) {

    this.elementId = ele;
    this.xmlPath = path;

    this.ROWS = rows;
    this.COLS = cols;
    this.HEIGHT = height;
    this.WIDTH = width;
    this.showOverlay = overlay;
    this.delay = delay;
    this.random = random;

    this.myTimer;
    this.doHover = false;

    this.aImg = [];
    this.mypics = new Array();

    $('#' + this.elementId).css({ 'width': (this.WIDTH * this.COLS), 'height': (this.HEIGHT * this.ROWS + 10) }).html('');

    var thisClass = this;

    $.get(this.xmlPath, function(xml) {
        $(xml).find('pic').each(function() {
            var item = new Apic();
            var $pic = $(this);
            item.weight = parseInt($pic.find('weight').text());
            item.title = $pic.find('title').text();
            item.description = $pic.find('description').text();
            item.url = $pic.find('url').text();
            item.small = $pic.find('small').text();
            item.medium = $pic.find('medium').text();
            item.large = $pic.find('large').text();
            thisClass.aImg.push(item.large);
            thisClass.mypics.push(item);
        });
        thisClass.render();
    });
}

PicGrid.prototype.render = function() {

    var thisClass = this;

    var arr = new Array(this.ROWS);
    for (var m = 0; m < this.ROWS; m++) {
        arr[m] = new Array(this.COLS);
        for (var n = 0; n < this.COLS; n++) {
            arr[m][n] = 0;
        }
    }
    var x = 0;
    var y = 0;
    var tt = new Array();
    while (this.mypics.length > 0) {
        if (arr[x][y] === 0) {
            var r = 0;
            var test = 0;
            var cl = 'left';
            do {
                if (this.random)
                    r = Math.round(Math.random() * (this.mypics.length - 1));
                var pic = this.mypics[r];
                var b = false;
                test++;
                for (var m = x; m < Math.min(x + pic.weight, this.ROWS - 1); m++) {
                    for (var n = y; n < Math.min(y + pic.weight, this.COLS - 1); n++) {
                        if (arr[m][n] !== 0) {
                            b = true;
                            break;
                        }
                    }
                }
            } while (test < 10 && ((x + pic.weight) > this.ROWS || (y + pic.weight) > this.COLS || b === true));
            if (test < 10) {
                if (y >= (this.COLS / 2)) { cl = 'right'; }
                var picurl = (pic.weight > 1) ? ((pic.weight > 2) ? pic.large : pic.medium) : pic.small;
                $('#' + this.elementId).append('<div id="' + this.elementId + '_k' + x + '_' + y + '" onclick="location.href=\'' + pic.url + '\';"></div>');
                var $cur = $('#' + this.elementId + '_k' + x + '_' + y).css(
                        { width: (this.WIDTH * pic.weight), height: (this.HEIGHT * pic.weight), left: (y * this.WIDTH), top: (x * this.HEIGHT) }
                    ).append(
                        '<img id="' + this.elementId + '_i' + x + '_' + y + '" alt="' + pic.title + '" src="' + picurl + '" />'
                    ).append(
                        '<div class="overlay">' + pic.title + '</div>'
                    ).append(
                        '<div class="dimbox"></div>'
                    ).append(
                        '<div class="hover" onclick="location.href=\'' + pic.url + '\';"><img class="' + cl + '" src="' + pic.large + '" alt="' + pic.title + '" /><b>' + pic.title + '</b><br />' + pic.description + ' <span class="more">click for more</span></div>'
                    ).hover(
                        function() {
                            $(this).parent().find('div.hover:visible').fadeOut(150, function() { $(this).parent().css('z-index', 1); });
                            if (thisClass.doHover) {
                                thisClass.myTimer = window.setTimeout('timedHover("' + $(this).attr('id') + '")', 500);
                            }
                        },
                        function() {
                            if (thisClass.doHover) {
                                clearTimeout(thisClass.myTimer);
                                $(this).parent().find('div.dimbox').fadeTo(100, 0.0);
                                $(this).find('div.hover').fadeOut(150, function() { $(this).parent().css('z-index', 1); });
                            }
                        }
                    );

                if (picurl.indexOf('http://') > -1) $cur.find('div.dimbox').css({ backgroundImage: 'none', backgroundColor: 'black' });
                $cur.find('div.dimbox').css({ width: (this.WIDTH * pic.weight - 2), height: (this.HEIGHT * pic.weight - 2) });
                $cur.find('div.hover').css({ width: (this.WIDTH * 12), height: (this.HEIGHT * 4) });
                $cur.find('div.hover > img').css({ width: (this.WIDTH * 4 - 2), height: (this.HEIGHT * 4 - 2) });

                tt[this.elementId + '_i' + x + '_' + y] = pic.weight;
                for (var m = x; m < (x + pic.weight); m++) {
                    for (var n = y; n < (y + pic.weight); n++) {
                        arr[m][n] = pic.weight;
                    }
                }
                y += pic.weight;
                this.mypics.splice(r, 1);
            } else {
                y++;
            }
        } else {
            y++;
        }
        if (y >= this.COLS) {
            y = 0;
            x++;
        }
        if (x >= this.ROWS) { break; }
    }
    // Initialisierungsbug-Wordaround im IE bei erster Einblendung
    if (ie) { $('#' + this.elementId).find('div.dimbox').hide().fadeTo(1, 0.0, function() { $(this).show(); }); }
    if (!this.showOverlay) { $('#' + this.elementId).find('div.overlay').remove(); }

    // Feld der größe nach sortieren
    var sa = new Object();
    var va = new Array();
    for (var tag in tt) { va.push(tt[tag]); }
    va.sort(Numsort);
    va.reverse();
    for (var i = 0; i < va.length; i++) { sa[va[i]] = new Array(); }
    for (var tag in tt) { sa[tt[tag]].push(tag); }

    var t = this.delay;
    for (var tags in sa) {
        for (var i = 0; i < sa[tags].length; i++) {
            // Einblendanimation sequenziell starten
            callAni(this, sa[tags][i], tags, t);
            t += 150;
        }
    }
    // Hover freigeben
    window.setTimeout(function() { thisClass.doHover = true; }, t + 200);
}

PicGrid.prototype.myani = function(e, w) {
    $('#' + e).animate({
        width: ((this.WIDTH * 1.1) * w), height: ((this.HEIGHT * 1.1) * w)
    }, 300).animate({
        width: (this.WIDTH * w - 2), height: (this.HEIGHT * w - 2)
    }, 100, null, function() { $('#' + e + ' + div.overlay').animate({ opacity: 0.7 }, 500); });
    $('#' + e + ' + div.overlay').css({ opacity: 0.0, fontSize: parseInt(this.WIDTH * w / 10), padding: parseInt(this.WIDTH * w / 25), height: parseInt(this.HEIGHT / 3 * w), width: parseInt((this.WIDTH * w) - 2 - (this.WIDTH * w / 12.5)) });
}

function callAni(obj, sa, tags, t) {
    window.setTimeout(function() { obj.myani(sa, tags) }, t);
}

function timedHover(e) {
    $ele = $('#' + e);
    $ele.css('z-index', 10);
    $ele.parent().find('div.dimbox').fadeTo(100, 0.7);
    if ($ele.find('div.hover > img').hasClass('left')) {
        $ele.find('div.hover').css('left', '-9px').fadeIn(250);
    } else {
        var a = '-9px';
        if (parseInt($ele.css('left')) + parseInt($ele.css('width')) < 600) a = '-' + (609 - parseInt($ele.css('left')) - parseInt($ele.css('width'))) + 'px';
        $ele.find('div.hover').css('right', a).fadeIn(250);
    }
}