/**
* @author richard
* Resize iframes automatically according to content height (and, optionally,
* width)
*/

var _IFrameAutoSize_called = false;

//call with ?debug_iframe_size to get debugging info
var _IFrameAutoSize_debug = location.search.match(/[?&]debug_iframe_size($|[=?&])/);

function IFrameAutoSize(iframe_id, do_width_too)
{
    var iframeDoc = document.getElementById(iframe_id).contentWindow.document;

    //find the height of the internal page:  NS/GECKO || IE, Safari
    var the_height = iframeDoc.height || iframeDoc.body.scrollHeight;
    var the_width = iframeDoc.width || iframeDoc.body.scrollWidth;

    var extra_height = parseInt(.014 * the_height);
	if (navigator.userAgent.indexOf("Firefox") != '-1') {
		extra_height += 30;
	}
    var extra_width = parseInt(.01 * the_width);

	//better for safari?
	/* Can't get this to work yet -- see island bbs page...
	if (navigator.userAgent.indexOf("Safari") > -1) {
		var the_height = iframeDoc.body.offsetHeight;
		var the_width = iframeDoc.body.offsetWidth;
		extra_height = 3000;
		extra_width = 25;
	}
	*/

    //I have yet to find a way to get document height in safari that does
    // not return the height of the containing iframe if it is greater than
    // that of the document. So, for Safari, the extra height/width must
    // only be applied once or the iframe will steadily grow!
    if (navigator.userAgent.indexOf("Safari") > -1) {
        if (_IFrameAutoSize_called) {
            extra_height = 0;
            extra_width = 0;
        } else {
            extra_height = 200;
            extra_width = 0;
        }
    }

    _IFrameAutoSize_debug && alert('width: ' + the_width + '+' + extra_width
        + "\nheight: " + the_height + '+' + extra_height);

    //need to adjust table width where it is at 100%
    var elements = iframeDoc.getElementsByTagName('table');
    for (var j = 0; j < elements.length; j++) {
        if (elements[j] && elements[j].getAttribute('width') == '100%') {
            elements[j].setAttribute('width', "96%");
            if (navigator.userAgent.indexOf("Firefox") != '-1'){
                elements[j].style.margin = "0 0";
            }
        }
    }

    if (do_width_too) {
		document.getElementById(iframe_id).width = the_width + extra_width;
	}

    document.getElementById(iframe_id).height = the_height + extra_height;

	/*
	if (navigator.userAgent.indexOf("Safari") > -1) {
		document.getElementById(iframe_id).height = the_height;
	}
	*/

    window.scrollTo(0,0);

    _IFrameAutoSize_called = true;
}
