/*
em.js
*/


$(window).load(function() { // this image handling code should run when all the images are loaded

    /* This adapted from JMetronome by Filipe Fortes,
       http://www.fortes.com/2008/jmetronome-using-jquery-to-keep-typographic-rhythm */
    var LINE_HEIGHT  = 24;
    var BASELINE_EMS = 1.7143;
    var BORDER_WIDTH = 10;
    $('img').parents('p').each(function() {
	var tallest = 0;
	$(this).find('img').each(function() {
	    var height = $(this).outerHeight();
	    tallest = Math.max(height, tallest);
	});
	if(tallest % LINE_HEIGHT == 0) {
	    tallest++;
	}
	else {
	    if(tallest % LINE_HEIGHT == LINE_HEIGHT - 1) {
		tallest = tallest + BORDER_WIDTH;
	    }
	}
	var lheight = Math.ceil(tallest/LINE_HEIGHT) * BASELINE_EMS;	
	$(this).css('line-height', lheight + 'em');
    });
});

jQuery(document).ready(function() { // this code can run as soon as the document itself is loaded   
 
    // this bit randomly picks an image for the top of the blog
    var MAXIMAGE = 2;
    var n = Math.round(Math.random() * MAXIMAGE - 0.5);
    $("#bonusImage").filter(":visible").append('<img alt="" src="/images/' + n + '.png" />');

    // expands or hides the months corresponding to the clicked-on year in the archives display
    $(".archivesYear").click(function() {
	var months_ul = $(this).parent().find('ul');
	if (months_ul.is(":visible")) {
	    months_ul.slideUp();
	    $(this).find('img').attr('src', '/images/expand-down.png');
	}
	else {
	    $(this).parent().find('ul').slideDown();
	    $(this).find('img').attr('src', '/images/expand-up.png');
	}
    });
    
    // displays baseline rhythm grid
    var cookieName = 'vertgrid';
    var cookieOpts = {expires: 7, path: '/'};
    var checkboxID = '#vertgridcheckbox';
    if($.cookie(cookieName) == 1) {
	$(checkboxID).attr('checked', 'true');
	gridOn(cookieName, cookieOpts);
    }
    else {
	$(checkboxID).removeAttr('checked');
	gridOff(cookieName, cookieOpts);
    }
    $(checkboxID).change(function() {
	if( $(checkboxID).attr('checked') ) {
	    gridOn(cookieName, cookieOpts);
	}
	else {
	    gridOff(cookieName, cookieOpts);
	}	    
    });
});

function gridOn(cookieName, cookieOpts) {
    $('body').css('background-image', 'url(/images/testrule.png)');
    $.cookie(cookieName, 1, cookieOpts);
}

function gridOff(cookieName, cookieOpts) {
    $('body').css('background-image', 'url(/images/bg.png)');
    $.cookie(cookieName, 0, cookieOpts); /* should unset the cookie, not just zero it out */
}

