var gDirList = null;
var	gReportRequest;
var gCurrPagePath = '';

function LoadHome()
{
	gCurrPagePath = getCookie( 'currPage' ); 
//alert(gCurrPagePath + ', ' + gCurrPagePath.length);
	if( gCurrPagePath == null || gCurrPagePath == undefined || gCurrPagePath.length == 0)
		gCurrPagePath = 'Welcome.html';

	getStuff();

	loadBanner();
	loadSidebar();
}

function loadBanner()
{
	var bannerText = '<div id="logo"><b>The Marin CERT Coalition</b></div><div id="byline"></div>';
	document.getElementById( 'banner' ).innerHTML = bannerText;
}

function setLogo( logoName, mentors )
{
	var text = '';
	
	// Pick a mentor at random
	var mentorPath1 = null;
	var mentorPath2 = null;
	if( mentors.length > 0 )
	{
		var len = mentors.length;
		var mentor1 = Math.floor( Math.random() * (len - 1) );
		var mentorPath1 = mentors[ mentor1 ].childNodes[0].nodeValue;
		var mentor2 = mentor1;
	
		while( mentor1 == mentor2 )
			mentor2 = Math.floor( Math.random() * (len - 1) );

		var mentorPath2 = mentors[ mentor2 ].childNodes[0].nodeValue;

		text += '<img src="' + mentorPath1 + '" alt="A Mentor Image" />';
	}
	
	text += '<img src="' + logoName + '" alt="The Marin CERT Coalition" />';
	
	if( mentors.length > 0 )
		text += '<img src="' + mentorPath2 + '" alt="A Mentor Image" />';

	// Put in the logo and images
	document.getElementById( 'logo' ).innerHTML = text;
}

function loadSidebar()
{
	var sidebarText = "<div id='siteTree'></div>";
	document.getElementById("sidebar").innerHTML = sidebarText;	
}

function setSidebar( xmlDoc )
{
	loadSiteTree( xmlDoc );
	document.getElementById("siteTree").innerHTML = gSiteTree;
	
//alert(gCurrPagePath.length);
	if( gCurrPagePath.length > 0 )
		loadCurrPage();
	else
		loadRoot();
}

// This adds site nodes to the tree ONLY. They are added when they first arrive from the database on opening.
// Reports are added to the tree later when they arrive.
function loadSiteTree( xmlDoc )
{
	// Make the trees
	gSiteTree = new dTree('gSiteTree');

	// The root is -1. Everything is a child of -1.
	gDirList = xmlDoc.getElementsByTagName( 'directory_0' );
	
	// There is only one top directory; it is entitled "tree" 
	var nextDir = gDirList[0];
	
	gSiteTree.add('S_' + 0, -1, 'Welcome', 'javascript:loadRoot();' );

	// Load the files in the directory first, then the subdirectories
	loadFileList( nextDir, 0 );

	// Now load the subdirectories
	loadSubDirList( nextDir, 0 );
	
	// Everything is now loaded
}	

function loadFileList( aDir, parent )
{
	var stop = false;
	for (var i=0; stop==false; i++)
	{
		try
		{
			var nextFile = aDir.getElementsByTagName( 'file_' + parent + '_' + i );
			var name1 = nextFile[0].getElementsByTagName( 'fileName' )[0].childNodes[0].nodeValue;
			name = name1.slice( 0, name1.indexOf( '.htm' ) );
			if( name != 'index' )
				gSiteTree.add('file_' + parent + '_' + i, 'S_' + parent, name, 'javascript:loadSiteNode();'  );
		}
		catch(e)
		{
			stop = true;
		}			
	}
}

function loadSubDirList( aDir, parent )
{
	var stop = false;
	for (var i=0; stop==false; i++)
	{
		try
		{
			var nextDir = aDir.getElementsByTagName( 'directory_' + parent + '_' + i );
			var name = nextDir[0].getElementsByTagName( 'name' )[0].childNodes[0].nodeValue;
			if( name != '_notes' )
				gSiteTree.add('S_' + parent + '_' + i, 'S_' + parent, name, 'javascript:loadSiteNode();', undefined, undefined, 'img/folder.gif', 'img/folderopen.gif', undefined );

			// Load the files in the directory first, then the subdirectories
			loadFileList( nextDir[0], parent + '_' + i );

			// Now load the subdirectories
			loadSubDirList( nextDir[0], parent + '_' + i );
		}
		catch(e)
		{
			stop = true;
		}			
	}
}

function loadContent( htmlContentArray, thePagePath )
{
	var ctr = htmlContentArray.length;
	var content = '';
	for(i=0; i<ctr; i++)
	{
		content += htmlContentArray[i].childNodes[0].nodeValue ;
	}

//alert( ctr + ', ' + content.length );
	// Urldecode it	
	document.getElementById( 'contents' ).innerHTML = URLDecode( content ) + "<div id='footer'></div>";
		
	loadFooter();

	// Set the cookie
	var now = new Date();
	var five_hours = new Date(now.getTime() + 1000 * 60 * 60 * 5);
	setCookie( 'currPage', thePagePath, five_hours );
}

function loadFooter()
{
	var text = '<p><center>Email: <a href="mailto:MarinCERTCoalition@gmail.com">The Marin County CERT coalition</a><br>Blog: <a href=" http://marincertcoalition.blogspot.com/" target="_blank">marincertcoalition.blogspot.com/</a><br/></center></p>';
	document.getElementById( 'footer' ).innerHTML = text;
	document.getElementById( 'footer' ).style.display = 'inline';
}

function loadCurrPage()
{
	getSiteNodeContent( gCurrPagePath );
}

function loadRoot()
{
	// Put in the Welcome Page content
	getSiteNodeContent( 'Welcome.html' );
}

function loadSiteNode()
{
	// Now load data from the DB. 				
	var sNodeId = gSiteTree.getSelected();
	
	// Now load
	if( sNodeId == 'S_0' )
	{
		loadRoot();
		return;
	}
	
	// Not the root
	var path = getCurrNodePath();	
	getSiteNodeContent( path );	
}

function getCurrNodePath()
{
	var nodeId = gSiteTree.getSelected();
	
	// Get the file path
//alert( nodeId );
	var path = '';
	if( nodeId.indexOf( 'file_' ) != -1 )
	{
		// This is a file
		var nextFile = gDirList[0].getElementsByTagName( nodeId );
		path = nextFile[0].getElementsByTagName( 'filePath' )[0].childNodes[0].nodeValue;
	}
	else
	{
		// This is a directory; get the first file in the directory
		// slice off 'S_'
		var pathNum = nodeId.slice(2);
//alert( 'file_' + pathNum + '_0' );

		var nextFile = gDirList[0].getElementsByTagName( 'file_' + pathNum + '_0' );
		if( nextFile[0] != undefined )
			path = nextFile[0].getElementsByTagName( 'filePath'  )[0].childNodes[0].nodeValue;
	}
	
	return path;
}

function getStuff()
{
	// Native XMLHttpRequest object: FireFox, Safari, Mozilla, netscape
	if (window.XMLHttpRequest)
			gReportRequest = new XMLHttpRequest();
	// IE/Windows ActiveX version
	else if (window.ActiveXObject)      
			gReportRequest = new ActiveXObject("Microsoft.XMLHTTP");
	
	if (gReportRequest == null)
	{
		document.getElementById('contents').innerHtml = "<p><span class=style4>Your browser does not support requests for data from a server. Please update the browser to a newer edition, \
								or change browsers to a more modern one. \n It may be that this is a temporary problem. If you think it is, try refreshing the page later.</span></p>";
		return;
	} 

	// Send the request
	try 
	{
		gReportRequest.onreadystatechange = processResponse;
		gReportRequest.open("POST", "GetLogoAndTree.php", true);	   
		gReportRequest.send(null);
	} catch(e) {
		document.getElementById( "contents" ).innerHtml = "<p><span class=style4>Your browser could not send a request for data to the server; This is probably a temporary problem, try refreshing the page later.</span></p>";
	}
}

function processResponse()
{
	// Check this one to see if it is "Done"
	if( gReportRequest.readyState == 4 || gReportRequest.readyState == "complete" )
	{
		if (gReportRequest.status == 200) 
		{
			var xmlDoc = gReportRequest.responseXML;
			if( xmlDoc == null )
			{
				document.getElementById('contents').innerHTML = '<p><span class=style4>The network connection is poor. Try refreshing the page or try again later.</span></p>' ;
				return;
			}
			
			errors = xmlDoc.getElementsByTagName( "errorcode" );
//alert(errors[0].childNodes[0].nodeValue);
			if( errors[0].childNodes[0].nodeValue == 0 )
			{
				setLogo( xmlDoc.getElementsByTagName( 'logoPath' )[0].childNodes[0].nodeValue, xmlDoc.getElementsByTagName( 'mentor' ) );
				
				setSidebar( xmlDoc );
			}
			else
			{
				var msg = xmlDoc.getElementsByTagName( "msg" );
				document.getElementById('contents').innerHTML = '<p><span class=style4>The network connection is poor. Try refreshing the page or try again later.</span></p>' ;
//				document.getElementById('contents').innerHTML = '<span class=style4>There is a problem Error:' + errors[0].childNodes[0].nodeValue + '; ' + msg[0].childNodes[0].nodeValue + '</span>' ;
				return;
			}
		}
	}
}

function getSiteNodeContent( path )
{
	// Native XMLHttpRequest object: FireFox, Safari, Mozilla, netscape
	if (window.XMLHttpRequest)
			gReportRequest = new XMLHttpRequest();
	// IE/Windows ActiveX version
	else if (window.ActiveXObject)      
			gReportRequest = new ActiveXObject("Microsoft.XMLHTTP");
	
	if (gReportRequest == null)
	{
		document.getElementById('contents').innerHtml = "<p><span class=style4>Your browser does not support requests for data from a server. Please update the browser to a newer edition, \
								or change browsers to a more modern one. \n It may be that this is a temporary problem. If you think it is, try refreshing the page later.</span></p>";
		return;
	} 

	// Send the request
	try 
	{
		gReportRequest.onreadystatechange = siteNodeResponse;
//alert("GetContentByPath.php?path=" + path);
		gReportRequest.open("POST", "GetContentByPath.php?path=" + path, true);	   
		gReportRequest.send(null);
	} catch(e) {
		document.getElementById( "contents" ).innerHtml = "<p><span class=style4>Your browser could not send a request for data to the server; This is probably a temporary problem, try refreshing the page later.</span></p>";
	}
}

function siteNodeResponse()
{
	// Check this one to see if it is "Done"
	if( gReportRequest.readyState == 4 || gReportRequest.readyState == "complete" )
	{
		if (gReportRequest.status == 200) 
		{
			var xmlDoc = gReportRequest.responseXML;
			if( xmlDoc == null )
			{
				document.getElementById('contents').innerHTML = '<p><span class=style4>The network connection is poor. Try refreshing the page or try again later.</span></p>' ;
				return;
			}
			
			errors = xmlDoc.getElementsByTagName( "errorcode" );
			if( errors[0].childNodes[0].nodeValue == 0 )
			{
				loadContent( xmlDoc.getElementsByTagName( "htmlArray" ), xmlDoc.getElementsByTagName( "path" )[0].childNodes[0].nodeValue );
			}
			else
			{
//				var message = xmlDoc.getElementsByTagName( "msg" );
//				document.getElementById('contents').innerHTML = '<p><span class=style4>The network connection is poor. Try refreshing the page or try again later.</span></p>' ;
//				document.getElementById('contents').innerHTML = '<p><span class=style4>Error saving:' + errors[0].childNodes[0].nodeValue + '; ' + message[0].childNodes[0].nodeValue + '</span></p>' ;
				// This puts up the Welcome.html page
				gSiteTree.s('0');
				gCurrPagePath = 'Welcome.html';
				loadCurrPage();
			}
		}
	}
}

function CERT_survey_validate()
{
	var now = new Date();
	var five_hours = new Date(now.getTime() + 1000 * 60 * 60 * 5);
	setCookie( 'currPage', "CERT_survey_thanks.html", five_hours );
}

function CERT_info_validate()
{
	var now = new Date();
	var five_hours = new Date(now.getTime() + 1000 * 60 * 60 * 5);
	setCookie( 'currPage', "CERT_info_thanks.html", five_hours );
}


