function find_max( min, max, truth ) {
    var r = max - min;
    var n = min + Math.ceil(r / 2);
    if (r / 2 < 1) {
        return truth(max) ? max : min;
    } else if(truth(n)) {
        return arguments.callee(n, max, truth);
    } else {
        return arguments.callee(min, n, truth);
    }
}

function find_min( min, max, truth ) {   
    var r = max - min;
    var n = max - Math.ceil(r / 2);
    if (r / 2 < 1) {
        return truth(max) ? max : min;
    } else if(truth(n)) {
        return arguments.callee(min, n, truth);
    } else {
        return arguments.callee(n, max, truth);
    }           
}

function fontHeightToFit(element, height) {
    return find_max(0, 500, function(i){
        element.style.fontSize = i + 'px';
        return element.offsetHeight <= height;
    });
}

function resizeTextContent(preferredFontSize) {
	var e = document.getElementById('textContent');
	var c = e.parentNode;
	var fontSize = preferredFontSize;
	e.style.fontSize = 0;				
	var maxFontSize = fontHeightToFit( e, c.offsetHeight );
	if ( maxFontSize < fontSize ) {
		fontSize = maxFontSize;
	}
	e.style.fontSize = fontSize;
	if ( c.offsetHeight > e.offsetHeight ) {
	    e.style.paddingTop = (c.offsetHeight - e.offsetHeight) / 2 + 'px';
	}
	else {
	    e.style.paddingTop = '0';
	}
}

function verticallyCenterTextInParent(textElement) {
    var height = textElement.offsetHeight;
	var width = textElement.offsetWidth;
    var area = textElement.parentNode;
    var areaHeight = area.offsetHeight;
	var areaWidth = area.offsetWidth;
	var shift = Math.max(0.0, (areaHeight - height)*0.5);
	textElement.style.marginTop = shift + 'px';	
}

function resizeImageToFitParent(image, widthFactor, heightFactor) {
    var height = image.height;
	var width = image.width;
    var area = image.parentNode;
    var maxHeight = area.offsetHeight * heightFactor;
	var maxWidth = area.offsetWidth * widthFactor;
	var heightRatio = height / maxHeight;
	var widthRatio = width / maxWidth;
	var ratio = 1.0 / Math.max(heightRatio, widthRatio);
	height *= ratio;
	width *= ratio;
	image.style.width = width + 'px';	
	image.style.height = height + 'px';
}

function verticallyCenterImageInParent(image) {
    var height = image.height;
	var width = image.width;
    var area = image.parentNode;
    var areaHeight = area.offsetHeight;
	var areaWidth = area.offsetWidth;
	image.style.bottom = (areaHeight - height)*0.5 + 'px';	
}

function horizontallyCenterImageInParent(image) {
    var height = image.height;
	var width = image.width;
    var area = image.parentNode;
    var areaHeight = area.offsetHeight;
	var areaWidth = area.offsetWidth;
	image.style.right = (areaWidth - width)*0.5 + 'px';	
}