var bustcachevar = 1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadstatustext = "<img alt='loading' src='../images/loading.gif' /> Requesting content...";

var loadedobjects = "";
var defaultcontentarray = new Object();
var bustcacheparameter = "";

//fcn to add a class name and remove it from element that has it upon fcn call
//clickedRel also is used to check for which Rel was clicked, so multiple anchors
//could have been selected for different rels and be displayed as such
function modClassName(justClicked, anchorArray, clickedRel)
{
	var classNameToSwap = 'selected';
	
	var regEx = /\s*selected/;
	
	var currentClassName;
	var currentRelValue;
	
	//sort thru anchorArray and remove className of 'selected' from element that currently has it
	for(k = 0; k < anchorArray.length; k++)
	{
 		currentClassName = anchorArray[k].className;
		currentRelValue = anchorArray[k].getAttribute("rel");
		
		if(currentClassName != '' && currentRelValue == clickedRel)
		{
			anchorArray[k].className = (currentClassName)?currentClassName.replace(regEx,''):'';
		}
	}
	
	//add class name 'selected' to clicked name to visually alter it
	//to show it's the currently selected item
	justClicked.className += ' ' + classNameToSwap;
}

function ajaxpage(url, containerid, targetobj)
{
	var page_request = false;
	
	//from: http://blogs.msdn.com/ie/archive/2006/01/23/516393.aspx
	var page_request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); 
	
	if (!page_request) //if page_request hasn't been set, create an error
	{
		alert('Error initializing XMLHttpRequest!');
	}

	if (url.indexOf("#default")!= -1)
	{ //if true simply show default content within container (versus fetch it via ajax)
		document.getElementById(containerid).innerHTML = defaultcontentarray[containerid];
		return;
	}

	document.getElementById(containerid).innerHTML = loadstatustext;
	
	page_request.onreadystatechange = function()
	{
		loadpage(page_request, containerid);
	}

	if (bustcachevar) //if bust caching of external page
	{
		bustcacheparameter = (url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime();
		page_request.open('GET', url+bustcacheparameter, true);
		page_request.send(null);
	}
}

function loadpage(page_request, containerid)
{
	if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1))
	{
		document.getElementById(containerid).innerHTML = page_request.responseText;
	}
}

function loadobjs(revattribute)
{
	if (revattribute!=null && revattribute!="")
	{ //if "rev" attribute is defined (load external .js or .css files)
		var objectlist = revattribute.split(/\s*,\s*/); //split the files and store as array
		
		for (var i=0; i<objectlist.length; i++)
		{
			var file = objectlist[i];
			var fileref = "";
			
			if (loadedobjects.indexOf(file)==-1)
			{ //Check to see if this object has not already been added to page before proceeding
				
				if (file.indexOf(".js")!=-1)
				{ //If object is a js file
					fileref = document.createElement('script');
					fileref.setAttribute("type","text/javascript");
					fileref.setAttribute("src", file);
				}

				else if (file.indexOf(".css")!=-1)
				{ //If object is a css file
					fileref = document.createElement("link");
					fileref.setAttribute("rel", "stylesheet");
					fileref.setAttribute("type", "text/css");
					fileref.setAttribute("href", file);
				}
			}

			if (fileref!="")
			{
				document.getElementsByTagName("head").item(0).appendChild(fileref);
				loadedobjects+=file+" "; //Remember this object as being already added to page
			}
		}
	}
}

function expandtab(tabcontentid, tabnumber)
{ //interface for selecting a tab (plus expand corresponding content)
	var thetab = document.getElementById(tabcontentid).getElementsByTagName("a")[tabnumber];
	
	if (thetab.getAttribute("rel"))
	{
		ajaxpage(thetab.getAttribute("href"), thetab.getAttribute("rel"), thetab);
		loadobjs(thetab.getAttribute("rev"));
	}
}

function savedefaultcontent(contentid)
{// save default ajax tab content
	if (typeof defaultcontentarray[contentid] == "undefined") //if default content hasn't already been saved
	{
		defaultcontentarray[contentid] = document.getElementById(contentid).innerHTML;
	}
}

//
// Function runs on window load, going through link tags looking for rel="loadHTML".
// These links receive onclick events that enable the image swap.
//
function startAjax()
{
	if (!document.getElementsByTagName){ return; }
	var anchorList = document.getElementsByTagName("a");
	
	var anchorArray = new Array();
	var counter = 0;
	
	var relValue = /ajaxcontentarea/i; //i allows for a case-insensitive match
	var matchRel = null;

	// loop through all anchor tags
	for (var i = 0; i < anchorList.length; i++)
	{
		//test for rel of which first part == ajaxcontentarea
		//put in rel some value where the beginning of the rel attribute value
		//equals ajaxcontentarea, and to use this to target different element
		//containers, simply add something to the end of the value,
		//ie: ajaxcontentarea2, ajaxcontentareaLast, etc
		
		//does the anchor have a rel attribute?
		if(anchorList[i].getAttribute("rel"))
		{
			//match the current rel to relValue and store result in matchRel
			matchRel = anchorList[i].getAttribute("rel").match(relValue);
		}
		
		//if the anchor has an href attribute AND has a matchRel...
		if (anchorList[i].getAttribute("href") && matchRel)
		{
			anchorArray[counter] = anchorList[i]; //store all anchors that pass above if test into new array
			
			//this is the part the gunks up IE7 when tested on local machine, due to urls of the type file:///
			//might be due to enhanced security settings since this works in IE6
			var modifiedurl = anchorArray[counter].getAttribute("href").replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/");
			
			anchorArray[counter].setAttribute("href", modifiedurl); //replace URL's root domain with dynamic root domain, for ajax security sake
			
			//eventually run some string fcn on the filename in the link to determine if web page or image and perform appropriate fcn as needed
			
			savedefaultcontent(anchorArray[counter].getAttribute("rel")); //save default ajax tab content
				
			anchorArray[counter].onclick = function()
			{
				ajaxpage(this.getAttribute("href"), this.getAttribute("rel"), this);
				modClassName(this, anchorArray, this.getAttribute("rel")); //add 'selected' to classname
				loadobjs(this.getAttribute("rev"));
				return false;
			}

			if (anchorArray[counter].className == "selected")
			{
				ajaxpage(anchorArray[counter].getAttribute("href"), anchorArray[counter].getAttribute("rel"), anchorArray[counter]); //auto load currently selected tab content
				loadobjs(anchorArray[counter].getAttribute("rev")); //auto load any accompanying .js and .css files
			}
			
			++counter;
		}
		
		matchRel = null; //reset matchRel
	}
}

function init()
{
	startAjax();
}

//
// addLoadEvent()
// Adds event to window.onload without overwriting currently assigned onload functions.
// Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
    	window.onload = func;
	}
	
	else
	{
		window.onload = function()
		{
			oldonload();
			func();
		}
	}
}

addLoadEvent(init);	// run onLoad