var fill = function() {
    /* reset & init */
    if (typeof mw == 'undefined') mw = $('.mid .box').width(), mb = $('.mid.box'), mx = $('.box.mixed'), s1 = $('.side:first'), s2 = $('.side:last'), x = mb.length ? mb : mx;
    var mh = $('.mid').height(), sw = s1.width(), lnk = s1.find('.box:has(ol):not(:has(img))');

    /* roughly fitting left col: first unhide previous as required, then if left col is higher than mid col, hide left col element(s). Finish by pixel fitting the left linkbox. */
    lnk.css('paddingTop','0').find('a').css('padding','3px'); /* first reset previous pixel fitting */
    while (mh - s1.height() > 0 && lnk.find('li:hidden').length) lnk.find('li:hidden').last().show();
    while (mh - s1.height() > 100 && s1.find('dl:hidden:not(.opt)').length) s1.find('dl:hidden:not(.opt)').last().show();
    if ($('.mid').position().top < 180) { /* left col is in place */
        while (s1.height() - mh > 100 && s1.find('dl:visible:not(:has(ol))').length) s1.find('dl:visible:not(:has(ol))').last().hide();
        while (s1.height() - mh > 0 && lnk.find('li:visible').length) lnk.find('li:visible').last().hide();
        var sh = s1.height(), lnum = lnk.find('li:visible').length, gap = Math.floor((mh - sh) / lnum); /* pixel fitting left linkbox */
        if (gap > 0) lnk.css('paddingTop',(mh - sh - lnum * gap)).find('li:visible a').css({'padding':(3 + Math.ceil(gap/2)) + 'px 3px ' + (3 + Math.floor(gap/2)) + 'px'});
    }

    /* if right col isn't browserpushed downleft, widen bottom midbox & fit right col, ELSE contract midbox & move thumbbox down */
    if (s2.position().top < 180) {
        /* reset: move right thumbbox back (if needed) & reset previous pixel fitting */
        mx.removeClass('beef').css({'width':'100%','paddingTop':'0'}).find('li').css('width', 'auto').end().find('span').css({'fontSize':'10px','lineHeight':'12px'}).filter('.th').css('width','48px').end().end().find('img').css({'width':'44px','height':'44px'}); /* first reset previous pixel fitting */
        if ($('body > .box.mixed').length) mx.appendTo(s2);

        /* if bottom midbox exists, widen it, ELSE remove right thumbox' bottom margin */
        if (mb.length) mb.css('width',(2*sw)+mw+32);
        x.css({'marginLeft':'auto','marginRight':'auto'});

        /* fitting right col: first unhide previous as required, then if right col is higher than mid col, hide right col element(s). Finish by pixel fitting the right thumbbox. */
        while (mh - s2.height() > 0 && s2.find('dl:hidden').length) s2.find('dl:hidden').last().show();
        while (s2.height() - mh > 0 && s2.find('dl:visible:not(:has(ol))').length) s2.find('dl:visible:not(:has(ol))').last().hide();
        var sh2 = s2.height(), gap = Math.min(Math.floor((mh - sh2) / 6), 48); /* pixel fitting; th's can grow to max 96 width (88x88 + 2px border) */
        if (gap > 0) mx.css('paddingTop',(mh - sh2 - 6*gap)).find('span').css({'fontSize':Math.round(10 + 1.4*gap/48) + 'px','lineHeight':Math.round(12 + 2*gap/48) + 'px'}).filter('.th').css({'width':(48 + gap) + 'px'}).end().end().find('img').css({'width':(44 + gap) + 'px','height':(44 + gap) + 'px'});
    } else { /* right col IS browserpushed downleft or bottomcenter */
        /* if midbox exists, contract it, ELSE style right thumbbox to take its place */
        if (mb.length) mb.css('width',mw); else mx.addClass('beef');
        x.css({'marginLeft':'1%','marginRight':'1%'});

        /* move right thumbbox to the mid-bottom of the page */
        mx.find('img').css({'width':92,'height':92}).end().find('span').css({'fontSize':'13px','lineHeight':'18px'}).filter(':first-child').css('width','98px');
        $('.foot').before(mx);

        /* if left col is in place, set mixed box width to (left + mid col) (or just mid col if midbox doesn't exist), ELSE set to full width. */
        var med = $('.mid').position().top < 180;
        mx.css({'width':(med ? (mb.length?sw+mw+28:mw) : '98%')}).find('li').css('width', '50%');

        /* if  midbox + thumbbox is higher than right col, show any previously hidden right col element(s) as needed */
        var xh = x.height();
        if (xh - s2.height() > 20) s2.find('dl:hidden:has(blockquote)').show(); /* restore the hidden quoteblock first */
        while (xh - s2.height() > 20 && s2.find('dl:hidden').length) s2.find('dl:hidden').last().show();

        /* if left col is in place, roughly fit right col (which was browserpushed bottomleft). */
        if (med) {
            if (s2.height() - xh > 20) s2.find('dl:visible:has(blockquote)').hide(); /* hide a quoteblock first */
            while (s2.height() - xh > 20 && s2.find('dl:visible:not(:has(ol))').length) s2.find('dl:visible:not(:has(ol))').last().hide();
        }
    }
    /* if page is short, make sure footer is at bottom of viewport */
	var dif = $(window).height() - ($(document.body).height() - $(".foot").css("margin-top").replace("px", ""));
	if (dif > 0) $(".foot").css({margin: dif + "px 0 0 0"});
}

$.fn.nextParentUntil = function(){return $(this).parent().nextUntil('div,dl');}

var collapse = function() { 
    if ($(window).width() < 600) 
        $('.jquery-more').html('(more...)').fadeIn().nextParentUntil().slideUp();
    else
        $('.jquery-more').hide().nextParentUntil().slideDown();      
}

$(document).ready(function() {
    /* crest init */
    $('.crest a img').roll();

    /* if appropriate, bind both the fill routine itself ánd its "resize event" binding to the Window load event */
    if ($('.side').length) { 
        $(window).load(fill).load(function () { $(this).resize(fill) });     
    } else { 
    /* text collapsing on homepage */
        $('.m').prev().append(' <a href="#" class="jquery-more" onclick="return false" style="display:none">(more...)</a>');
        $('.jquery-more').collapser({target:'nextParentUntil',effect:'slide',changeText:true,expandHtml:'(more...)',collapseHtml: '',expandClass:'',collapseClass:''});
        $(window).load(collapse).load(function () { $(this).resize(collapse) });
    }

    /* color ramps */
    $('.box ol:not(:has(img)), .box.mixed ol').colorRamp();
    
    
    /* beehive tracking */
    $('.box.screen a,.box.thumb a').mousedown(function () { new Image().src= 'show.php?t&' + $(this).attr('class').replace('t ',''); });

    /* jquery.zoom.js controller */
    var home = jQuery(".box.thumb.popular").length ? true : false;
    if (jQuery.cookie('zoom') !== '0') {
        jQuery(".zoom-y").attr("checked",true); jQuery(".zoom-n").removeAttr("checked");
        home ? jQuery(".box.thumb img").zoom({type:'hover'}) : jQuery(document.body).zoom({type:'click',spd:420});
    } else { jQuery(".zoom-y").removeAttr("checked"); jQuery(".zoom-n").attr("checked",true); }
    jQuery(".box dt input").change(function() {
        if ($(this).val() === '1') {
            jQuery(".zoom-y").attr("checked",true); jQuery(".zoom-n").removeAttr("checked");
            home ? jQuery(".box.thumb img").zoom({type:'hover'}) : jQuery(document.body).zoom({type:'click',spd:420});
            jQuery.cookie('zoom', '1', { expires: 90, path: '/' });
        } else {
            jQuery(".zoom-y").removeAttr("checked"); jQuery(".zoom-n").attr("checked",true);
            home ? jQuery(".box.thumb img").unbind() : jQuery(document.body).unbind("click");
            jQuery.cookie('zoom', '0', { expires: 90, path: '/' });
        }
    });
});

/* jquery.zoom.js (includes jquery.cookie.js) */
jQuery.fn.zoom = function (conf) {
    var cfg = jQuery.extend({
        type: 'click', // click or hover(intent)
        spd: 270,      // zoom speed
        bw: 7,         // total border-width + margins of the imgzoom box other than its own negative margin (if any)
        im: 15,        // margin from image-edge to window-edge if image is larger than screen
        cl: 'jquery-zoom',
        li: '/js/ajax_small.gif',
        liw: 64,
        lih: 64
    }, conf);

    var cfgHover = {
        sensitivity: 3, // default 7; the higher, the quicker the trigger
        interval: 200,
        timeout: 0,
        out: doOut,
        over: doOver
    };

    // preload "loading..." image (spinner)
    var spinner = jQuery('<img/>');
    spinner.attr('src', cfg.li).css({position:'absolute',left:(240 - cfg.liw)/2 + 'px',top:(180 - cfg.lih)/2 + 'px',width:cfg.liw+'px',height:cfg.lih+'px',border:'0'}).addClass('spinimg');

    // attach click or hoverIntent event
    return cfg.type == 'click' ? this.click(doOver) : this.hoverIntent(cfgHover);

    function doOut(e) {}
    function doOver(e) {
        // Make sure the target-element is a link (or an element inside a link)
        var ele = jQuery(e.target);
        var lnk = ele.is('a') ? ele : ele.parents('a'); // If it's not an a, check if any of its parents is
        if (cfg.type == 'click') lnk = (lnk && lnk.is('a') && lnk.attr('href').search(/(.*)\.(jpg|jpeg|gif|png|bmp|tif|tiff)$/gi) != -1) ? lnk : false; // If it was an a or child of an a, make sure it points to an image
        var i = (lnk && lnk.find('img').length) ? lnk.find('img') : false; // See if the clicked link contains an image
        // Only continue if a link pointing to an image was clicked
        if (lnk) {
            lnk.setli = function () {
                if (i) {
                    if (cfg.type == 'click') {
                        var offs = i.offset();
                        spinner.css({left:offs.left + i.outerWidth()/2 - cfg.liw/2,top:offs.top + i.outerHeight()/2 - cfg.lih/2}).appendTo(document.body);
                    } else lnk.css({position:'relative'}).append(spinner);
                }
            };
            lnk.setnli = function () {
                if (i && jQuery('.spinimg').length) jQuery('.spinimg').detach();
            };

            // The URI to the image we are going to display
            var displayImgSrc = cfg.type == 'hover' ? i.attr('src').replace('240x180.jpg', '300x300.jpg') : lnk.attr('href');


            // If an imgzoom with this image is already open dont do anything
            // else if another imgzoom is still open, close it and continue
            if (jQuery('div.' + cfg.cl + ' a img[src="' + displayImgSrc + '"]').length) {
                if (cfg.type == "click") return false;
            } else if (jQuery('div.' + cfg.cl).length) {
                jQuery('div.' + cfg.cl + ' a.imgZoomClose').click();
            }

            // This function is run once the displayImgSrc-img has loaded (below)
            var preloadOnload = function () {
                // The clicked-link is faded out during loading, fade it back in
                lnk.setnli();

                // create the target image div (before zoom) and set its dimensions and position
                var dimele = i ? i : lnk; // The element used to retrieve dimensions of imgzoom before zoom (either clicked link or img inside)
                var offset = dimele.offset(); // Offset of clicked link (or image inside)
                if (cfg.type == "click") {
                    var iz = jQuery('<div><a href="' + lnk.parent().parent().find('a:not(:has(img))').attr('href') + '"><img src="' + displayImgSrc + '" alt="" /></a></div>').css('position', 'absolute').appendTo(document.body);
                    var bfor = {
                        width: dimele.outerWidth() - 2* cfg.bw,
                        height: dimele.outerHeight() - 2* cfg.bw,
                        left: offset.left,
                        top: offset.top
                    };
                } else { // hover
                    var iz = jQuery('<div><a href="' + lnk.attr('href') + '"><img src="' + displayImgSrc + '" alt="" /></a></div>').css('position', 'absolute').appendTo(document.body);
                    var bfor = {
                        width: dimele.outerHeight() - 2 * cfg.bw,
                        height: dimele.outerHeight() - 2 * cfg.bw,
                        left: offset.left + (dimele.outerWidth() - dimele.outerHeight())/2,
                        top: offset.top,
                        opacity: '0.7'
                    };
                }
                // dimensions of the iz *after* it is zoomed out
                var aft = { width: iz.outerWidth(), height: iz.outerHeight(), 'padding-bottom': '3px', 'opacity': '1'};
                var windowDim = { width: jQuery(window).width(), height: jQuery(window).height() };

                // ensure imgzoom isn't wider/taller than screen
                if (aft.width > (windowDim.width - cfg.im * 2)) {
                    var nWidth = windowDim.width - cfg.im * 2;
                    aft.height = (nWidth / aft.width) * aft.height;
                    aft.width  = nWidth;
                }
                if (aft.height > (windowDim.height - cfg.im * 2)) {
                    var nHeight = windowDim.height - cfg.im * 2;
                    aft.width  = (nHeight / aft.height) * aft.width;
                    aft.height = nHeight;
                }

                if (cfg.type == "click") { // on click, center zoom in browser
                    aft.left   = (windowDim.width - aft.width) / 2 + jQuery(window).scrollLeft();
                    aft.top    = (windowDim.height - aft.height) / 2 + jQuery(window).scrollTop();
                } else { // on hover, center zoom over hovered element
                    aft.left   = bfor.left - (aft.width - bfor.width)/2;
                    aft.top    = bfor.top - (aft.height - bfor.height)/2;
                }
                // add the zoom close button
                var closeButton = jQuery('<a class="imgZoomClose" href="#">Close</a>').appendTo(iz).hide();

                // now animate the zoom from its small size to its large size, and then fade in the close-button
                iz.addClass(cfg.cl).css(bfor).animate(aft, cfg.spd, "swing", function () {
                    closeButton.fadeIn(cfg.spd/2);
                });

                // this function closes the zoom
                var closeZoom = function () {
                    closeButton.fadeOut(cfg.spd/2, function () {
                        iz.animate(bfor, cfg.spd/2, function () {
                            lnk.css('visibility', 'visible');
                            iz.remove();
                        });
                    });
                };

                if (cfg.type == "hover") {
                    iz.hover(
                        function() { clearTimeout(myTimer); },
                        function() { myTimer = setTimeout(closeZoom,500); }
                    );
                }
                closeButton.click(function() { closeZoom(); return false; });
            };

            // preload image
            var preload = new Image();
            preload.onload = preloadOnload;
            preload.src = displayImgSrc;
            if (!preload.complete) { lnk.setli(); }

            // return false from the click so the browser doesn't actually follow the link...
            if (cfg.type == "click") return false;
        }
    }
};
// Close image zooms when user hits esc
$(document).keydown(function (e) {
    if (e.keyCode == 27) {
        $('div.jquery-image-zoom a').click();
    }
});

/* End zoom */


