var isStacked = false;
var delay = 1000;
var menuIsOpen = 1;
var closedMenuWidth = 0;
var submenuIsOpen = 1;
var menu;
var submenu;
var submenuClosed;
var contentElement;
var openMenuWidth;
var openSubMenuWidth;
var menuClosed;
var fragID = "";
var fontsize = 19;

// The variable 'usingIEStyles' is defined in austlitStyles-ie.js, which should
// only be included for Internet Explorer.  It is a shortcut that lets us know
// that special CSS styles are in use for IE, which affects how the layout
// adjustments in this file are performed.  The check directly below ensures
// that the variable is defined whether IE is in use or not (but is set to
// false).
if (! $defined(window.usingIEStyles)) {
	window.usingIEStyles = false;
}

var TOPLEVEL_FIXED_CONTENT_DIV_ID = 'content';
var TOPLEVEL_FULL_CONTENT_DIV_ID = 'contentFull';

var FIXED_CONTENT_DIV_ID = 'fixedContent';
var FULL_CONTENT_DIV_ID = 'contentInner';

var FULL_TEXT_SEARCH_IFRAME_ID = 'fullTextIFrame';
var FULL_TEXT_VIEW_IFRAME_ID = 'fullTextViewIFrame';

var FONT_SIZE = 19;
var FIXED_CONTENT_MAX_WIDTH = FONT_SIZE * 36;
var CONTENT_RIGHT_MARGIN = FONT_SIZE * 3;

var SHOW_DEBUG = false;

var logWindowShown = false;
var debugWindow = null;

function debugLog (message) {
	if (!SHOW_DEBUG) {
		return;
	}

	if (!$defined (window.console) || !window.console) {
		if (!logWindowShown || !debugWindow) {
			openDebugWindow();
		}

		try {
			debugWindow.document.getElementById("display").value += ("[" + new Date().toString() + "]: " + message + "\n");
		} catch (error) { }
	}
	else {
		console.log (message);
	}
}

function openDebugWindow() {
	if (!SHOW_DEBUG) {
		return;
	}

	try {
		debugWindow = window.open("/common/debugger.html","debug","height=500,width=1000");
		logWindowShown = true;
	} catch (error) { }
}

function closeDebugWindow()
{
	if (!SHOW_DBEUG) {
		return;
	}

	if (debugWindow) {
		try {
			debugWindow.close();
		} catch (error) { }
	}
}

function getMemberList (element) {
	var str;

	for (s in element) {
		str += " " + s + "\n";
	}

	return str;
}

function menuHighlightLink(elem) {
	var current = $('submenu').getElementsByClassName("currentMenuSelection");
	for (var i = 0; i < current.length; i++) {
		current[i].className = "";
	}
	elem.className = "currentMenuSelection";
}

function highlightMenu() {

	if (document.location.href) {
		var url = document.location.href;
	} else {
		url = document.location;
	}
	var urlFragments = url.split('/');

	var menuLink = "";
	var baseURL = "";
	if (urlFragments.length > 2) {
		baseURL = "http://" + urlFragments[2];
	}
	// highlight in the grey menu based on fragment id (stylesheet already
	// highlights based on current page)
	var fragmentLinkArr = urlFragments[urlFragments.length - 1].split('#');
	if (fragmentLinkArr.length > 1) {
		fragID = fragmentLinkArr[1];
		if (fragID && fragID !== "") {

			var submenuLinkDivs = document.getElementById('submenuItems')
					.getElementsByTagName('div');
			for (var i = 0; i < submenuLinkDivs.length; i++) {
				var nextLink = submenuLinkDivs[i];
				var nextLinkA = nextLink.getElementsByTagName('a')[0];
				if (nextLinkA.href == url) {
					if (nextLink.className != "subLink" && nextLink.className != "subsubLink") {
						nextLink.className = "highlightLink";
					} else {
						nextLinkA.className = "currentMenuSelection";
					}
				}
			}
			// var focusElem = document.getElementById(fragID);
			// document.location="#" + fragID;
		}
	}
	// highlight in red menu based on current page
	if (urlFragments.length >= 4) {
		menuLink = urlFragments[3];
	}
	if (menuLink === "") {
		menuLink = "#";
	}
	if (menuLink !== "" && menuLink) {
		var menuLinkDivs = document.getElementById('menuItems').getElementsByTagName('div');

		for (var i2 = 0; i2 < menuLinkDivs.length; i2++) {
			var nextLinkDiv = menuLinkDivs[i2];
			var nextLink = nextLinkDiv.childNodes.item(0);
			while (nextLink && nextLink.nodeType != 1)
			{
				nextLink = nextLink.nextSibling;
			}
			if (nextLink && nextLink.href == baseURL + "/" + menuLink) {

				nextLinkDiv.className = "highlightRedLink";
			}
		}
	}

}

function setWidthWithMaximum (element, width, maxWidth, rightMargin) {

	if (rightMargin > -1) {
		width = width - rightMargin;
	}

	if (maxWidth > -1)	{
		width = width > maxWidth ? maxWidth : width;
	}
    if (element.setStyle && typeof element.setStyle == "function"){
	   element.setStyle ('width', width - 1);
	   element.setStyle ('width', width);
    }
}

function setWidthWithMaximumById (elementId, width, maxWidth, rightMargin) {
	element = $(elementId);

	if (!element)
		return;

	setWidthWithMaximum (element, width, maxWidth, rightMargin);
}

function determineLeftOffset() {
	var offset = 0;
	// On full-width pages, the inner element gives the right offset.
	var offsetElement = $('contentInner');

	// On fixed-width pages, the top-level content element should be used.
	if (!offsetElement) {
		offsetElement = $('content');
	}
	if (offsetElement) {
		offset = offsetElement.offsetLeft;
	}
	return offset;
}

function getTopLevelContentDiv() {
	// Search order is crucial here; EditTopic pages have an unrelated div with
	// id 'content', but use 'contentFull' as their top level container.
	var topLevel = $('contentFull');

	if (!topLevel) {
		topLevel = $('content');
	}

	return topLevel;
}

function setContentWidth() {

   debugLog ('[setContentWidth() start]');
   if (document.body){
	debugLog ('usingIEStyles = ' + usingIEStyles);
	// The div with the id 'fixedContent' will be restricted to a maximum width
	var fixedContentElement = $('fixedContent');

	debugLog ('fixedContentElement not null?: ' + fixedContentElement != null);

	// The div with the id 'printHeader' seems to be invisible on most pages.
	var printHeaderElement = document.getElementById('printHeader');

	// Grab the full width of the window
	var newWidth = document.body.clientWidth;

	debugLog ('newWidth: ' + newWidth);

	newWidth -= determineLeftOffset();

	debugLog ('left offset: ' + determineLeftOffset());
	debugLog ('newWidth: ' + newWidth);

	// Retrieve the top level content div (currently, depends on whether we
	// are viewing a fixed-width or full-width page).
	var contentDiv = getTopLevelContentDiv();

	// On fixed-width pages, the top-level content div width must be set.
	if (contentDiv && contentDiv.id == 'content') {
		contentDiv.setStyle ('width', newWidth);
	}

	// This operation is only need on Opera and FF3 to ensure that full width
	// actually display at full width - on pages where 'contentInner' doesn't
	// contain 'width: 100%' elements (like the tables on work pages), they are
	// a bit reluctant to do the right thing...
	// NOTE: A check is added for IE styles here because if we do this with the
	// IE div styles, we end up with an unwanted horizontal scroll bar.  Evil.
	if (!usingIEStyles) {
		setWidthWithMaximumById ('contentInner', newWidth, -1, -1);
	}

	// When printing pages, don't restrict fixedContent width
	if (printHeaderElement && printHeaderElement.className == 'visible') {
		fixedContentElement.setStyle ('width', 'auto')
	}
	else {
		setWidthWithMaximum (fixedContentElement, newWidth,
			FIXED_CONTENT_MAX_WIDTH, CONTENT_RIGHT_MARGIN);
	}

	// Resize the full text iframes, if they are present
	setFullTextWidths(newWidth);
	setFullTextHeight();

	// Ensure that the content area has focus (important for some browsers?)
	if (!document.location.href.match("EditTopic")) {
		contentDiv.focus();
	}
	var ele = document.getElementById("focusField");
	// if results are being displayed don't jump to focus field
	var ele2 = document.getElementById("rc");
	if (ele && !ele2) {
		ele.focus();
		if (ele2 && (!fragID || fragID === "")) {
			document.location = "#fixedContent";
		}
	}

	// position the format form in result listings
	var ele3 = $("formResults");
	var fedele = $("fedSidebar");
	if (ele3) {
		var resultsWidth;
		if (fedele) {
			resultsWidth = newWidth - 27 * fontsize;
		} else {
			resultsWidth = newWidth - 14 * fontsize;
		}
		ele3.setStyle('width', resultsWidth);
	}
   }
   debugLog ('[setContentWidth() end]');
}
function openMenu() {
	if (menuIsOpen === 0) {
		if (submenuIsOpen === 0) {
			submenu.setProperty('class', 'left18em invisible');
			contentElement.setProperty('class', 'pleft23em');
		} else {
			contentElement.setProperty('class', 'pleft36em');
			submenu.setProperty('class', 'left18em visible');
		}
		submenuClosed.setProperty('class', 'left18em');
		menu.setProperty('class', 'visible');
		menuIsOpen = 1;
		setContentWidth();
		var logoimg = $('logoimage');
		if (logoimg) {
			logoimg.setProperty("class", "invisible");
		}
		var logosub = $('logosubtitle');
		if (logosub) {
			logosub.setProperty("class", "invisible");
		}
	}
}
function closeMenu() {

	if (menuIsOpen == 1) {
		menu.setProperty('class', 'invisible');
		if (submenuIsOpen == 1) {
			submenu.setProperty('class', 'left2em visible');
		} else {
			submenu.setProperty('class', 'left2em invisible');
		}
		submenuClosed.setProperty('class', 'left2em');
		if (submenuIsOpen === 0) {
			contentElement.setProperty('class', 'pleft7em');
		} else {
			contentElement.setProperty('class', 'pleft20em');
		}
		menuIsOpen = 0;
		setContentWidth();
		var logoimg = $('logoimage');
		if (logoimg) {
			logoimg.setProperty("class", "");
		}
		var logosub = $('logosubtitle');
		if (logosub) {
			logosub.setProperty("class", "");
		}
	}

}
function openSubMenu() {

	if (submenuIsOpen === 0) {
		if (menuIsOpen == 1) {
			contentElement.setProperty('class', 'pleft36em');
			submenu.setProperty('class', 'left18em visible');
		} else {
			contentElement.setProperty('class', 'pleft20em');
			submenu.setProperty('class', 'left2em visible');
		}
		submenuIsOpen = 1;
		setContentWidth();
	}
}
function closeSubMenu() {

	if (submenuIsOpen == 1) {
		if (menuIsOpen == 1) {
			contentElement.setProperty('class', 'pleft23em');
			submenuClosed.setProperty('class', 'left18em');
			submenu.setProperty('class', 'invisible');
		} else {
			contentElement.setProperty('class', 'pleft7em');
			submenu.setProperty('class', 'left2em invisible');
		}
		submenuIsOpen = 0;
		setContentWidth();
	}

}
function highlightColorRed(elem) {
	elem.style.backgroundColor = "#dc4a3f";
}

function highlightColorGrey(elem) {
	elem.style.backgroundColor = "#6a868c";
}

function menuColor(elem) {
	elem.style.backgroundColor = "";
}


function onFontResize(e, args) {
	setContentWidth();
}

function init() {

	debugLog ('init!');
	TextResizeDetector.addEventListener(onFontResize, null);
	TextResizeDetector.TARGET_ELEMENT_ID = 'fixedContent';

	if (document.getElementById('menuStartsOpen')) {
		menuIsOpen = 1;
	} else {
		menuIsOpen = 0;
	}

	if (document.getElementById('submenuStartsOpen')) {
		submenuIsOpen = 1;
	} else {
		submenuIsOpen = 0;
	}

	menu = $('menu');

	contentElement = $('contentInner');

	if (!contentElement) {
		contentElement = $('content');
	}

	submenu = $('submenu');
	submenuClosed = $('submenuClosed');
	menuClosed = $('menuClosed');
	// only add events if the stacked banner is present

   
	if (menuClosed) {

		menuClosed.addEvent('click', function () {
			openMenu();
		});
		if ($('submenuButton') && $('submenuButton').className != 'invisible') {
			submenuClosed.addEvent('click', function () {
				openSubMenu();
			});
		}
		if ($('menuOpen')) {
			$('menuOpen').addEvent('click', function () {
				closeMenu();
			});
		}
		if ($('submenuOpen')){
			$('submenuOpen').addEvent('click', function () {
				closeSubMenu();
			});
		}
	}

	setContentWidth();

	highlightMenu();
}

function getFrameDocument (frame) {
	debugLog ('getFrameDocument()');
	if (!frame) {
		debugLog ('frame == null!');
		return;
	}

	var frameDocument = frame.contentDocument;
	if (!frameDocument) {
		frameDocument = frame.contentWindow.document
		debugLog ('ie frame retrieval, document not null: ' + (frameDocument != null));
	}
	else {
		debugLog ('non-ie frame retrieval, document not null: ' + (frameDocument != null));
	}

	return frameDocument;
}

function getSubFrameDocument (parentFrame, subFrameId) {
	debugLog ('[getSubFrameDocument() start]');
	var frameDocument = getFrameDocument (parentFrame);

	if (!frameDocument) {
		return null;
	}

	var subFrame = frameDocument.getElementById (subFrameId);
	if (!subFrame) {
		debugLog ("Couldn't find sub-frame '" + subFrameId + "'");
		return null;
	}

	var subFrameDocumentElement = getFrameDocument (subFrame);

	debugLog ('[getSubFrameDocument() end]');
	return subFrameDocumentElement;
}

function setFullTextWidths(width) {
  if (usingIEStyles && $('div-content')) {
    var offsetLeft = $('div-content').getPosition().x;
    var bodyWidth = document.body.clientWidth;

    // A few pixels extra (probably to account for the scroll bar again)
    var newWidth = bodyWidth - (offsetLeft + 20);

    // alert ('offsetLeft: ' + offsetLeft + '\nbodyWidth: ' + bodyWidth + "\nnewWidth: " + newWidth);

    $('div-content').setStyle ('width', newWidth + 'px');
  }

  var tocDiv = $('div-toc-open');

  if (tocDiv) {
    contentDiv = $('div-content');

    if (tocDiv.getSize().y > contentDiv.getSize().y) {
      contentDiv.setStyle ('height', tocDiv.getSize().y + 'px');
    }
  }


	var ifrm = $(FULL_TEXT_SEARCH_IFRAME_ID);

	if (!ifrm) {
		ifrm = $(FULL_TEXT_VIEW_IFRAME_ID)
	}

	if (ifrm) {
		debugLog('Setting width (' + width + ') of full text iframe.');

		// innerContent = $('contentInner');
		setWidthWithMaximum(ifrm, width, -1, FONT_SIZE);
		// setWidthWithMaximum(innerContent, width, -1, CONTENT_RIGHT_MARGIN);
	}
}

function setFullTextHeight() {
  debugLog ('[setFullTextHeight() start]')

	var ifrm = $(FULL_TEXT_SEARCH_IFRAME_ID);

	if (ifrm) {
		debugLog ('Setting height for fulltext search/browse iframe.');

		ifrmDocument = getFrameDocument (ifrm);
		ifrm.setStyle ('height', ifrmDocument.body.scrollHeight + 20);
	}
	else {
		ifrm = $(FULL_TEXT_VIEW_IFRAME_ID);

		if (ifrm) {
			debugLog ('Setting height for fulltext viewing iframe...');

			contentDocumentHeight = getSubFrameDocument (ifrm, 'content').body.scrollHeight;
			tocDocumentHeight = getSubFrameDocument (ifrm, 'toc').body.scrollHeight;

			debugLog ('content frame height: ' + contentDocumentHeight);
			debugLog ('toc frame height: ' + tocDocumentHeight);

			ifrm.setStyle ('height', (contentDocumentHeight > tocDocumentHeight ? contentDocumentHeight : tocDocumentHeight) + 50);
		}
	}

	debugLog ('[setFullTextHeight() end]');
}

function printFullText()
{
	/*
	ifrm = document.getElementById ('fullTextViewIFrame');

	if (ifrm != null) {
		doc = ifrm.contentDocument;
		// oldWidth = doc.getElementById("toc").style.width;
		// doc.getElementById("toc").style.width = "0px"

		doc.getElementById('content').focus();
		fullTextViewIFrame.content.print();

		// doc.getElementById("toc").style.width = oldWidth;
	}
	*/

	ifrm = document.getElementById (FULL_TEXT_SEARCH_IFRAME_ID);

	if (!ifrm) {
		ifrm = document.getElementById (FULL_TEXT_VIEW_IFRAME_ID)

		if (ifrm) {
			// Print full text view here
		}
	}
	else {
		// Print search results here
		fullTextIFrame.print();
	}
}
function showModalMessage(msg){
	 var msgDiv = document.createElement("div");
	 // CSS and markup for msgBog generated by SpiffyCorners http://www.spiffycorners.com/
	 var msgBox = '<b style="display:block">' +
	 		'<b style="display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;margin-left:3px;margin-right:3px;padding-left:1px;padding-right:1px;border-left:1px solid #f7f7f7;border-right:1px solid #f7f7f7;background:#f2f2f2"><b></b></b>' +
	 		'<b style="display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;margin-left:1px;margin-right:1px;padding-right:1px;padding-left:1px;border-left:1px solid #fdfdfd;border-right:1px solid #fdfdfd;background:#f1f1f1"><b></b></b>'+
  			'<b style="display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;margin-left:1px;margin-right:1px;border-left:1px solid #f1f1f1;border-right:1px solid #f1f1f1;"></b>' +
  			'<b style="display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;border-left:1px solid #f7f7f7;border-right:1px solid #f7f7f7"></b>' +
  			'<b style="display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;border-left:1px solid #f2f2f2;border-right:1px solid #f2f2f2"></b></b>' +
  			'<div style="background:#eeeeee;padding:20px">' +
			msg +
  			'</div>' +
  			'<b style="display:block">' +
  			'<b style="border-left:1px solid #f2f2f2;border-right:1px solid #f2f2f2;display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee;"></b>' +
  			'<b style="border-left:1px solid #f7f7f7;border-right:1px solid #f7f7f7;display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee"></b>' +
  			'<b style=" margin-left:1px;margin-right:1px;border-left:1px solid #f1f1f1;border-right:1px solid #f1f1f1;display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee"></b>' +
  			'<b style="margin-left:1px;margin-right:1px;padding-right:1px;padding-left:1px;border-left:1px solid #fdfdfd;border-right:1px solid #fdfdfd;background:#f1f1f1;display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee"><b></b></b>' +
  			'<b style="margin-left:3px;margin-right:3px;padding-left:1px;padding-right:1px;border-left:1px solid #f7f7f7;border-right:1px solid #f7f7f7;background:#f2f2f2;display:block;height:1px;overflow:hidden;font-size:.01em;background:#eeeeee"><b></b></b></b>';
	 msgDiv.innerHTML = msgBox;
  	 msgDiv.style.fontSize = "14px";
	 msgDiv.style.fontWeight = "bold";
	 msgDiv.style.textAlign = "center";
	 msgDiv.style.position = "absolute";
	 if(usingIEStyles){
	 	msgDiv.style.width = msg.length + "em";
	 } 
	 document.body.appendChild(msgDiv);
	 msgDiv.style.left = ((document.body.clientWidth - msgDiv.clientWidth)/2) + "px";
	 msgDiv.style.top = ((document.body.clientHeight - msgDiv.clientHeight) /2) + "px";
}

TextResizeDetector.USER_INIT_FUNC = init;

window.addEvent('load', function() {
    init();
});

window.onresize = setContentWidth;
window.onunload = setContentWidth;
window.onfocus = setContentWidth;

// added kkf 15jul09 to support hide/show

function toggle(toggleText, displayText, showPrompt, hidePrompt) {
	var ele = document.getElementById(toggleText) ;
	var text = document.getElementById(displayText) ;
	if(ele.style.display == "block") {
    		ele.style.display = "none" ;
		text.innerHTML = showPrompt ;
  	}
	else {
		ele.style.display = "block" ;
		text.innerHTML = hidePrompt ;
	}
} 



