var bInitDone=false;
var g_sTitleClass='.celltitle.celltitle0.misctitle.misctitle0.';
var arrHideElems=['info', 'collapse', 'image'];
var g_initIMG='.';
var hiliteSave;
var g_bCollapseAllDone=false, g_bCollapseAllInProgress=0;

InitFireFox_insertCode();

window.document.onclick = function (e) { return toggleInfo(document.all ? event.srcElement : e.target);}

function IsTitle( obj ) { return g_sTitleClass.indexOf('.'+obj.className.toLowerCase()+'.')>=0; }


function writeIMGtogglers() {
	if( bInitDone ) return;
	try
	{	var prevID='';
		var arrDiv=document.body.getElementsByTagName('DIV');
		var htmlDiskette='<img src="images/diskette2.png" border="0" align="absmiddle">&nbsp;';

		for( var i=0; i<arrDiv.length; i++ )
			if( arrDiv[i].className.toUpperCase().indexOf('TITLE')>=0)
			{	var ID=arrDiv[i].id;
				var arrSpan=arrDiv[i].getElementsByTagName('SPAN');
				var b_aDLwritten=false, b_TogglerWritten=false, bIDisMacroSet=(ID.substr(0,3)=='set');

				if( ID )
					for( var j=0; j<arrSpan.length; j++ )
						if( arrSpan[j].className.toUpperCase().indexOf('TOGGLER')>=0 )
						{	toggler=arrSpan[j];
							toggler.style.display='inline';
							toggler.insertAdjacentHTML('AfterBegin',
													   '&nbsp;&nbsp;<img id="collapse'+ID+'" class="Collapse" src="images/collapse.gif"'+
															(bIDisMacroSet?' style="display:-moz-inline-box;display:inline-block;"':'')+
													   '><img class="Expand" id="expand'+ID+'" src="images/expand.gif"'+
															(bIDisMacroSet?' style="display:none">Show/hide macros':'>info'));
							b_TogglerWritten=true;
							//write collapser on the bottom of infoXXX DIV
							for(var k=0, obj=arrDiv[i].nextSibling; k<10 && (obj!=null); k++, obj=obj.nextSibling)
							{	if( obj.nodeType!=1) continue; //document.ELEMENT_NODE
								if( obj.id.substr(0,4)=='info' )
								{ obj.insertAdjacentHTML('BeforeEnd', '<img class="Collapse" src="images/collapse.gif" style="float:left;position:relative;left:2ex;top:-4.5ex; display:block" onClick="return collapseInfo(\''+ID+'\');">');
									break; }
								if( g_sTitleClass.indexOf('.'+obj.className.toLowerCase()+'.')>=0 ) break;
							}
							//diskette inside A
//							for(k=0,aDL=toggler.previousSibling; k<5 && (aDL!=null); k++,aDL=aDL.previousSibling)
//								if( aDL.nodeType==1 )
//									if( aDL.tagName.toUpperCase()=='A' )
//										if( aDL.getElementsByTagName('IMG').length==0)
//										{	aDL.insertAdjacentHTML('AfterBegin', htmlDiskette);
//											b_aDLwritten=true;
//										}
							break;
						} //toggler
					//SPAN: end loop
				if( !b_aDLwritten )
					{	arrSpan=arrDiv[i].getElementsByTagName('A');
						if( arrSpan.length && arrSpan[0].href.length && arrSpan[0].getElementsByTagName('IMG').length==0)
							arrSpan[0].insertAdjacentHTML('AfterBegin', htmlDiskette);
					}
			} //loop DIV
		bInitDone=true;
	}
	catch(ex) {alert(ex);}
}


function onOpenDetectURLanchor() {
	var i=document.URL.lastIndexOf('#'); if( i<0 ) return;
	expandInfo( document.URL.substr( i+1 ) );
	var obj=document.getElementById(document.URL.substr( i+1 ));
	if( obj )
		obj.style.backgroundColor='yellow';
}


function fetchIDobj( origin ) {
	try {
		if( origin==null ) return null;
		if( origin.tagName.toUpperCase()=='A' ) return null;
		if( '.canvas.macrosset.'.indexOf('.'+origin.className.toLowerCase()+'.')>=0 ) return null;

		for(var i=0, obj=origin; (i<5) && (obj!=null); i++, obj=obj.parentNode)
			if( obj.tagName.toUpperCase()=='DIV')
				if( IsTitle( obj )) { if( obj.id.length>0) return obj; else break;}
//				else // catch miscTitleDL
//					if( obj.className.toUpperCase().indexOf('TITLEDL')>=0 )
//						for( var j=0, sib=obj.previousSibling; (j<25) && (sib!=null); j++, sib=sib.previousSibling)
//							if( sib.nodeType==1 )
//								if( sib.tagName.toUpperCase()=="DIV")
//									if( IsTitle( sib )) if( sib.id.length ) return sib; else break; //inner loop
	} catch(ex) {}
	return null;
}


// rets TRUE if error (handy for onClick)
function toggleInfo (origin) {
	var objID=fetchIDobj( origin );
	if( objID==null )
		if( g_bCollapseAllDone ) return !restoreCell( origin );
		else return true;

	if( !expandInfo( objID )) collapseInfo( objID.id );
	return false;
}


//rets TRUE for success, need to reverse in onClick
function expandInfo( argID ) {
	var objID, obj;
	try
	{	switch( typeof argID )
		{	case 'string': case 'number': objID=document.getElementById( argID );	break;
			case 'object': objID=argID; break;
			case 'undefined': return false;
		}
		if( objID==null ) return false;

		//intitialize IMGs and find details cell block
		var cell=null, ID=objID.id, bSearchIMG=(g_initIMG.indexOf('.'+ID+'.')==-1) && ID.substr(0,3)!='set';

		for(obj=objID.nextSibling; obj!=null; obj=obj.nextSibling)
		{	if( obj.nodeType!=1) continue; //document.ELEMENT_NODE
			if( IsTitle( obj )) break;

			if( cell==null )
				if( obj.id.indexOf('info')==0 ) cell=obj;

			if( bSearchIMG )
				if( obj.tagName.toUpperCase()=="IMG" )
				{	if( obj.src='' ) { obj.src=obj.alt; obj.alt=''; } }
				else
				{	var children=obj.getElementsByTagName('IMG');
					var L=children.length;
					for( var i=0; i<L; i++ )
					{	var img=children[i];
						if( img.src.length==0 )
						{	img.src=(img.alt.indexOf('/')==-1 ? 'images/':'')+img.alt;
							img.alt='';
							if(img.style.display=='none') img.style.display='block';
						}
					}
				}
		}
		if(bSearchIMG) g_initIMG+=ID+'.';	 //don't search for IMGs next time for this object ID

		var obj=(cell==null) ? cell=document.getElementById('info'+ID) : cell;
		if( !obj )
		{	obj=objID.nextSibling; if( obj.nodeType!=1 ) obj=obj.nextSibling;
			if( ID.substr(0,3)=='set' )
			{	if( document.getElementById( 'expand'+ID).style.display=='none') return false;
				obj.style.display='block';
			}
			if( obj.className!='cell' ) obj=null;
		}
		if( obj )
		{	if ((obj.style.display.length | obj.className.length)==0) return false; // already expanded
			obj.style.display='';
			if (obj.className!='cell') { obj.className=''; restoreCell( obj ); }
		}
		obj=document.getElementById('image'+ID); if(obj) obj.style.display='block';
		obj=document.getElementById('expand'+ID); if(obj) obj.style.display='none';
		obj=document.getElementById('collapse'+ID); if(obj) obj.style.display='inline';

		//check if MacrosSet is collapsed
		obj=GetParentElementByClassName( objID, 'MacrosSet' );
		if( obj && obj.style.display=='none' ) obj.style.display='block';

		if( !g_bCollapseAllInProgress )
			if( !IsElementVisible( window, objID )) scrollIntoView( window, objID, 't');
	}
	catch(ex) {return false;}
	return true;
}


function collapseInfo( ID ) {
	var obj, objID, i;
	for( i=0; i<arrHideElems.length; i++)
	{	obj=document.getElementById(arrHideElems[i]+ID);
		if( obj ) obj.style.display='none';
	}
	objID=document.getElementById(ID);
	if( ID.substr(0,3)=='set' )
	{	obj=objID.nextSibling; if(obj.nodeType!=1) obj=obj.nextSibling;
		obj.style.display='none';
	}
	obj=document.getElementById('expand'+ID); if(obj) obj.style.display='';
	if( !g_bCollapseAllInProgress && obj!=null)
		if( !IsElementVisible( window, obj ))
			ScrollIntoView( window, obj, 't');
}


function restoreCell( nearObj ) {
	//whether a misc/cell title
	if( g_sTitleClass.indexOf('.'+nearObj.className.toLowerCase()+'.')>=0 )
		for(var i=0, obj=nearObj.nextSibling; i<10 && (obj!=null); i++, obj=obj.nextSibling)
		{	if( obj.nodeType!=1) continue; //document.ELEMENT_NODE
			if( IsTitle( obj )) break;
			if( obj.className=="cell")	{ obj.style.display=''; return true; }
		}
	//fix 'cell' block visibilty after collapse-ALL....check children
	var arrDiv=nearObj.getElementsByTagName('DIV');
	if( arrDiv.length )
		for(i=0, obj=arrDiv[i]; i<arrDiv.length; i++, obj=arrDiv[i])
			if( obj.className=="cell") { obj.style.display=''; return true; }
	//fix 'cell' block visibilty after collapse-ALL....check parent
	obj=GetParentElementByClassName( nearObj, 'cell' );
	if( obj ) { obj.style.display=''; return true; }
	return false;
s}


function toggleALL() {
	var bDoExpand, bShowMacroSet;
	try {
		var obj=document.getElementById('expandAll');
		obj.style.display=(obj.style.display!='none')?'none':'block';

		obj=document.getElementById('collapseAll');
		obj.style.display=(obj.style.display!='none')?'none':'block';
		bDoExpand=(obj.style.display=='block');
		g_bCollapseAllDone=true;
	} catch (e) {}

	g_bCollapseAllInProgress=true;

	var divs=document.body.getElementsByTagName('DIV');
	for (var i=0;i<divs.length;i++)
		if( bShowMacroSet ) { bShowMacroSet=0; divs[i].style.display='block'; }
			else if( divs[i].id.substr(0,3)=='set' ) bShowMacroSet=true;
				else if (divs[i].id.substr(0,4)=='info')
					if( bDoExpand ) expandInfo( divs[i].id.substr(4) );
					else collapseInfo( divs[i].id.substr(4) );

	if( !bDoExpand )
		for (var i=0;i<divs.length;i++)
			if (divs[i].className.toLowerCase()=='cell') divs[i].style.display='none';
			else if( bShowMacroSet ) { bShowMacroSet=0; divs[i].style.display='block'; }
				else if( divs[i].id.substr(0,3)=='set' ) bShowMacroSet=true;

	g_bCollapseAllInProgress=0;
	return false;
}



function InitFireFox_insertCode()
{
	if(typeof HTMLElement=="undefined" || HTMLElement.prototype.insertAdjacentElement)
		return;
	HTMLElement.prototype.insertAdjacentElement =
		function( where, parsedNode )
		{	switch (where.toLowerCase())
			{	case 'beforebegin': this.parentNode.insertBefore(parsedNode,this); break;
				case 'afterbegin': this.insertBefore(parsedNode,this.firstChild); break;
				case 'beforeend': this.appendChild(parsedNode); break;
				case 'afterend':
					if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
					else this.parentNode.appendChild(parsedNode);
					break;
			}
		}
	HTMLElement.prototype.insertAdjacentHTML =
		function( where, htmlStr )
		{	var r = this.ownerDocument.createRange();
			r.setStartBefore(this);
			var parsedHTML = r.createContextualFragment(htmlStr);
			this.insertAdjacentElement(where,parsedHTML)
		}
	HTMLElement.prototype.insertAdjacentText =
		function( where, txtStr )
		{	var parsedText = document.createTextNode(txtStr);
			this.insertAdjacentElement(where,parsedText);
		}
}

function ScrollIntoView( win, obj, alignment /* 'bmt' */) {
	var T = GetPageOffsetTop(obj);
	var B = T + obj.offsetHeight;
	var winT = GetScrollTop(win);
	var winHt = GetWindowHeight(win);
	var winB = winT + winHt;

	if (T >= winT && B <= winB) return false;

	var toY;
	switch (alignment.toLowerCase()) {
		case 'b': toY=B - winHt + 5; break;
		case 'm': toY=(T+B)/2-winHt/2; break;
		default: toY=T-5; //top
	}
	//alert( toY);
	win.scrollTo(0, toY);
}

function IsElementVisible( win, obj ) {
	var T=GetPageOffsetTop( obj );
	var B=T+obj.offsetHeight;
	var winT=GetScrollTop( win );
	var winB=winT+GetWindowHeight( win );
	return  (T >= winT && B <= winB);
}

function GetParentElementByTagName( obj, tag ) {
	for( var objParent=obj; objParent; objParent=objParent.parentNode )
		if( objParent.tagName.toLowerCase()==tag.toLowerCase() )
			return objParent;
	return null;
}

function GetParentElementByClassName( obj, cls ) {
   var clslc=cls.toLowerCase();
	for( var objParent=obj; objParent && (objParent.nodeType==1); objParent=objParent.parentNode )
		if( objParent.className.toLowerCase()==clslc ) return objParent;
	return null;
}

function GetPageOffsetTop( obj ) {
	for( var y = 0, cur=obj; cur!=null; cur=cur.offsetParent ) y += cur.offsetTop;
	return y;
}

function GetScrollTop(win) {
	if ("pageYOffset" in win)
		return win.pageYOffset; // all except Explorer
	if ("documentElement" in win.document && "scrollTop" in win.document.documentElement)
		return win.document.documentElement.scrollTop; // Explorer 6 Strict Mode
	if ("scrollTop" in win.document.body)
		return win.document.body.scrollTop;
	return 0;
}

function GetWindowHeight(win) {
	if ("innerHeight" in win)
		return win.innerHeight; // all except Explorer
	if ("documentElement" in win.document && "clientHeight" in win.document.documentElement)
		return win.document.documentElement.clientHeight; // Explorer 6 Strict Mode
	if ("clientHeight" in win.document.body)
		return win.document.body.clientHeight; // other
	return 0;
}
