/**
 * Grid-A-Licious(tm)
 * Version 2.0
 * Copyright (c) 2008-2011 Suprb - info(at)suprb(dot)com
 *
 */
(function ($) {
    $.fn.grid = function (options, item, r, scroll) {
        if (item === undefined) item = false;
        if (scroll === undefined) scroll = false;
        if (r === undefined) r = true;
        var defaults = {
            min_cols: 4,
            gap: 20,
            speed: 80,
            duration: 150,
            width: 200,

            animateUpdate: true,
            postPath: '.post',
            postWidePath: '.postwide',
            postWiderPath: '.postwider',
            postWidestPath: '.postwidest',
            allColsPath: '.allcols',
            openColsPath: '.opencols',
            center: true
        };
        mcc = defaults.min_cols;
        options = $.extend(defaults, options);
        var $gridbox = this;
        var l, columns, _c, columns, alt, offx, offy, hh, biggest = 0,
            total = 0,
            count = 0,
            footer = 0,
            offy = 0,
            offx = 0,
            start = 0;
        $gridbox.css("position", "relative");
        var maxy = new Array();
        offy = parseInt($gridbox.css("padding-top").replace('px', ''));
        offx = parseInt($gridbox.css("padding-left").replace('px', ''));
        if (options.max_cols && options.min_cols > options.max_cols) options.min_cols = options.max_cols;
        layout(r);

        function highest(cols) {
            zzz = $gridbox.find('.post').size() * options.speed;
            for (x = 0; x < maxy.length; x++) {
                if (maxy[x] > biggest) {
                    biggest = parseInt(maxy[x])
                }
            }
            $('body').append('<span id="interval-tmp"></span>');
            $("#interval-tmp").fadeOut(zzz, function () {
                $gridbox.css("height", biggest + "px");
                $('#interval-tmp').remove()
            });
            if (options.center) {
                countboxes = $gridbox.find('.post').size();
                co = columns;
                if (countboxes > co) {
                    countboxes = co
                }
                cp = (countboxes * options.width) + ((countboxes - 1) * options.gap);
                if (settings.animateUpdate) {
                    $gridbox.animate({
                        width: cp
                    }, {
                        duration: options.duration,
                        easing: options.easing
                    })
                } else {
                    $gridbox.css('width', cp)
                }
                $gridbox.css({
                    marginLeft: 'auto'
                });
                $gridbox.css({
                    marginRight: 'auto'
                })
            }
        }
        function layout(r) {
            var $posts = $(options.postPath, $gridbox);
            var $postsWide = $(options.postWidePath, $gridbox);
            var $postsWider = $(options.postWiderPath, $gridbox);
            var $postsWidest = $(options.postWidestPath, $gridbox);
            var $allCols = $(options.allColsPath, $gridbox);
            var $openCols = $(options.openColsPath, $gridbox);
            var width = options.width;
            count = 1;
            columns = Math.max(options.min_cols, parseInt($(window).width() / (width + options.gap)));
            if (options.max_cols && columns > options.max_cols) columns = options.max_cols;
            $posts.css('width', width + 'px');
            $postsWide.css('width', width * 2);
            $postsWider.css('width', width * 3 + options.gap * 2);
            $postsWidest.css('width', width * 4 + options.gap * 3);
            countboxes = $gridbox.find('.post').size();
            co = columns;
            if (countboxes > co) {
                countboxes = co
            }
            cp = (countboxes * options.width) + ((countboxes - 1) * options.gap);
            columns_inner = Math.max(options.min_cols, cp / (width + options.gap));
            $allCols.css('width', cp);
            if (cp > (5 * options.width) + ((countboxes - 1) * options.gap)) cp = (5 * options.width) + (countboxes - 1) * options.gap;
            $openCols.css('width', cp);
            for (x = 0; x < columns_inner; x++) {
                maxy[x] = 0
            }
            $posts.each(function (i) {
                if (item === false) $(this).removeClass('open');
                total = i + 1;
                var $p = this;
                var $post = $(this);
                var pos, cursor, w, alt = 0;
                var newleft, oldleft, newtop, oldtop;
                w = (Math.floor($post.outerWidth() / width));
                cursor = 0;
                for (x = 0; x < columns_inner - (w - 1); x++) {
                    cursor = maxy[x] < maxy[cursor] ? x : cursor
                }
                if (w > 1) {
                    pos = cursor;
                    for (var x = 0; x < w; x++) {
                        alt = Math.max(alt, maxy[pos + x])
                    }
                    for (var x = 0; x < w; x++) {
                        maxy[pos + x] = parseInt($post.outerHeight()) + options.gap + alt
                    }
                    newleft = pos * (width + options.gap) + offx;
                    newtop = alt + offy;
                    if (newleft !== oldleft) {
                        if (options.animateUpdate === false || item === "#" + $post.attr('id')) {
                            $post.css({
                                'left': pos * (width + options.gap) + offx,
                                'top': alt + offy
                            })
                        }
                        setTimeout(function () {
                            if (r === true) {
                                if ($post.hasClass('open')) $post.fadeOut(options.duration);
                                else $post.fadeIn(options.duration)
                            }
                            count++;
                            check(item, r, columns);
                            $post.animate({
                                left: newleft,
                                top: newtop,
                                opacity: 1
                            }, {
                                duration: options.duration,
                                easing: options.easing
                            })
                        }, i * (options.speed))
                    } else {
                        $post.css({
                            'left': pos * (width + options.gap) + offx,
                            'top': alt + offy
                        })
                    }
                } else {
                    newleft = cursor * (width + options.gap) + offx;
                    newtop = maxy[cursor] + offy;
                    if (newleft !== oldleft) {
                        if (options.animateUpdate === false) {
                            $post.css({
                                'left': cursor * (width + options.gap) + offx,
                                'top': maxy[cursor] + offy
                            });
                            highest()
                        }
                        setTimeout(function () {
                            if (r === true) {
                                if ($post.hasClass('open')) $post.fadeOut(options.duration);
                                else $post.fadeIn(options.duration)
                            }
                            check(item, r, columns);
                            count++;
                            $post.animate({
                                left: newleft,
                                top: newtop,
                                opacity: 1
                            }, {
                                duration: options.duration,
                                easing: options.easing
                            })
                        }, i * (options.speed))
                    } else {
                        $post.css({
                            'left': pos * (width + options.gap) + offx,
                            'top': alt + offy
                        })
                    }
                    maxy[cursor] += $post.outerHeight() + options.gap
                }
                $post.fadeIn(options.duration)
            })
        }
        function check(item, r, columns) {
            if (count >= total) {
                if (item) {
                    var oy = parseInt($(item).css("top").replace('px', '') - options.gap);
                    var zzz = $gridbox.find('.post').size() * options.speed;
                    $(item + ' .single').delay(zzz).fadeTo(options.duration, 1);
                    click = true
                }
                if (scroll) {
                    $('html,body').animate({
                        scrollTop: oy
                    }, options.duration, options.easing)
                }
                options.animateUpdate = true;
                highest(columns)
            }
        }
    }
})(jQuery);
