/*******************************************************************************
* Initialize
*******************************************************************************/
// preload images
$(window).bind('load', function() {
    var preload = [
        '/images/home/checkbox-0.gif',
        '/images/home/checkbox-1.gif'
    ];
    $(document.createElement('img')).bind('load', function(){
        if(preload[0]) this.src = preload.shift();
    }).trigger('load');
});

/*******************************************************************************
* Main
*******************************************************************************/
$(document).ready(function() {

    // vision test checkboxes as images
    $('#visionTest input[@type="checkbox"]').each(function() {
        var $input = $(this);
        $input
            .css('visibility', 'hidden')
            .wrap('<span style="position: relative; display: inline-block;"></span>')
            .filter(':checked')
                .before('<img src="images/home/checkbox-1.gif" width="16" height="16" style="position: absolute; top: 0; left: 0;" />')
            .end()
            .not(':checked')
                .before('<img src="images/home/checkbox-0.gif" width="16" height="16" style="position: absolute; top: 0; left: 0;" />')
            .end();
        var $img = $input.prev('img');
        $input.bind('click.visionTest', function() {
            if ($input.is(':checked')) {
                $img.attr('src', 'images/home/checkbox-1.gif'); 
            } else {
                $img.attr('src', 'images/home/checkbox-0.gif'); 
            }
        });
        $img.click(function() {
            $input.trigger('click!');
            $input.trigger('click.visionTest');
        });
        var inputWidth = $input.width();
        var inputHeight = $input.height();
        var imgWidth = $img.width();
        var imgHeight = $img.height();
        if (imgWidth > inputWidth) {
            $img.css( 'margin-left', -1 * Math.round((imgWidth-inputWidth)/2) );
        } else {
            $img.css( 'margin-left', Math.round((inputWidth-imgWidth)/2) );
        }
        if (imgHeight > inputHeight) {
            $img.css( 'margin-top', -1 * Math.round((imgHeight-inputHeight)/2) );
        } else {
            $img.css( 'margin-top', Math.round((inputHeight-imgHeight)/2) );
        }
        $img.css({
            'margin-top': (parseInt($img.css('margin-top')) || 0) + (parseInt($input.css('margin-top')) || 0) + 'px',
            'margin-right': (parseInt($img.css('margin-right')) || 0) + (parseInt($input.css('margin-right')) || 0) + 'px',
            'margin-bottom': (parseInt($img.css('margin-bottom')) || 0) + (parseInt($input.css('margin-bottom')) || 0) + 'px',
            'margin-left': (parseInt($img.css('margin-left')) || 0) + (parseInt($input.css('margin-left')) || 0) + 'px'
        });
        
    });
    
});