// JavaScript Document

var _targetElemID; // string: The ID of the target HTML element inside which the AJAX Grid will load.
var ProcessedArray = new Array(); // An array to hold the items that will be used in the grid.
var lastSortElem; // integer - the last dimension in ProcessedArray that was sorted upon.
var lastSortDir; // string: the direction of the last sort - either "asc" or "desc"
var xhr; // our XMLHttpRequest object.

/* GetXMLHttpRequestObject() does some basic browser-sniffing and returns an appropriate XMLHttpRequestObject.
   parameter: handler (function object):
	 	sets onload (for mozilla) or onreadystatechange (for IE) to the function specified. */
function GetXMLHttpRequestObject(handler)
{
	if (window.ActiveXObject)
	{
		var o = new ActiveXObject("MSXML2.XMLHTTP");
		o.onreadystatechange = handler
		
		return o;
	}
	else if (window.XMLHttpRequest)
	{
		var o = new XMLHttpRequest();
		o.onload = handler;
		return o;
	}
	else
	{
		return null;
	}
}


/* retrieves an XMLHttpRequest object from GetXMLHttpRequestObject.
   opens and sends the request to the XML resource.
	 parameter targetElemID (string) should contain the ID attribute of the target HTML element inside which to load data.
	 init() is called from the <body> tag's onload attribute. */
function init(targetElemID)
{
	_targetElemID = targetElemID;
	// send the Handler() function as a parameter to GetXMLHttpRequestObject. Handler will be invoked after the XML data has loaded.
	xhr = GetXMLHttpRequestObject(Handler);
	if (xhr != null)
	{
		xhr.open("GET", "FileListXML.asp", true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		xhr.send(null);
	}
	else
	{
		alert("Couldn't create XMLHttpRequest Object.");
	}
}

/* Handler() is a generic event-handling function written to work with 
   both Mozilla and IE implementations of XMLHttpRequest.*/
function Handler()
{
	/* object-sniffing (window.XMLHttpRequest) for Mozilla browsers. 
	   xhr.readyState and xhr.status (4 is ready, 200 is status:OK) apply to IE. */
	if (window.XMLHttpRequest || (xhr.readyState == 4 && xhr.status == 200))
	{
		ProcessRequest();
	}
}

/* ProcessRequest() iterates through the DOM tree of the XML document 
   and extracts the useful bits to push to ProcessedArray.*/
function ProcessRequest()
{		
	if (xhr.responseXML.documentElement)
	{
		var docElem = xhr.responseXML.documentElement
		var NodeList = docElem.childNodes;
		for (var i=0; i< NodeList.length; i++)
		{
			try
			{
				var CurrentNode = NodeList[i];
				var FileName = CurrentNode.getElementsByTagName("Name")[0].firstChild.nodeValue;
				var Url = CurrentNode.getElementsByTagName("Url")[0].firstChild.nodeValue;
				var DateLastModified = CurrentNode.getElementsByTagName("DateLastModified")[0].firstChild.nodeValue;
				var PrimitiveDate = parseInt(Date.parse(DateLastModified));
				var FunctionCall = "OpenFile(&quot;" + Url + "&quot;);";
				ProcessedArray.push(
					[
						PrimitiveDate, 
						FileName, 
						"<a onclick=\"" + FunctionCall + "\">" + FileName + "</a><img width=\"0\" height=\"0\" class=\"CSSHackImage\" />",
						"<a onclick=\"" + FunctionCall + "\">" + DateLastModified + "</a><img width=\"0\" height=\"0\" class=\"CSSHackImage\" />"
					]
				);
			}
			catch(e)
			{
				/*
				You might be wondering about this empty catch block...
				I was running into an error iterating the DOM tree in firefox (using ArrayObj[i].getElementsByTagName("TAGNAME"))
				
				I couldn't figure out how to stop the error from occuring, but noticed if 
				I wrapped the contents of this for loop inside a try...catch block,
				the code magically worked anyway... go figure. 
				
				Not that I want to encourage a bad coding practice!! :-p */
			}
		}
		BuildGrid();
	}		
}
/* BuildGRid steps through ProcessedArray and builds an HTML string 
   containing a table with the data, and places the HTML into the page. */
function BuildGrid()
{
	if (ProcessedArray.length)
	{
		var sHTML = new String();
		sHTML += "<table class=\"AJAXGrid\">";
		sHTML += "<tr class=\"HeaderRow\">";
		sHTML += "<td><a title=\"Click to sort by File Name.\" onclick=\"" + GetSortLink(1) + "\"><span>File Name</span>";
		sHTML += "<img width=\"11\" height=\"10\" src=\"" + GetSortImage(1) + "\" class=\"SortImage\" /></a></td>";
		sHTML += "<td><a title=\"Click to sort by Date Last Modified.\" onclick=\"" + GetSortLink(0) + "\"><span>Date Last Modified</span>";
		sHTML += "<img width=\"11\" height=\"10\" src=\"" + GetSortImage(0) + "\" class=\"SortImage\" /></a></td>";
		
		sHTML += "</th>";
		for (var i=0; i<ProcessedArray.length; i++)
		{
			sHTML += "<tr class=\"ItemRow\" onmouseover=\"this.style.backgroundColor='#ccc';\" onmouseout=\"this.style.backgroundColor='';\">";
			sHTML += "<td>" + ProcessedArray[i][2] + "</td><td>" + ProcessedArray[i][3] + "</td>";
			sHTML += "</tr>";
		}
		document.getElementById(_targetElemID).innerHTML = sHTML;
	}
	else
	{
		document.getElementById(_targetElemID).innerHTML = "Sorry, there was a problem retrieving data!";
	}
}

/* DoSort calls the Sort function with the specified array dimension and sort direction.
   Then, it saves the dimension and direction that were just sorted on to lastSortElem and lastSortDir.
	 Lastly, it calls BuildGrid() to re-build the HTML table. */
function DoSort(elem, dir)
{
	Sort(ProcessedArray, elem, dir);
	lastSortElem = elem;
	lastSortDir = dir;
	BuildGrid();
}
/* GetSortLink() is a helper function that outputs a string of javascript.
   This function is used by BuildGrid to supply sortable column headers to the HTML table. 
	 Parameters:
	 	elem (integer): The array dimension to plug into the 'DoSort' function call. */
function GetSortLink(elem)
{
	if (elem == lastSortElem && lastSortDir == "asc")
	{
		return("javascript:DoSort(" + elem + ", 'desc');");
	}
	else
	{
		return("javascript:DoSort(" + elem + ", 'asc');");
	}
}
/* GetSortImage returns the path the the upward, 
   downward or blank sort images, depending on the parameter specified. 
	 Parameters:
    elem (integer) - an array dimension. The function checks this parameter against lastSortElem to determine which 
    image path to return. */
function GetSortImage(elem)
{
	if (elem == lastSortElem)
	{
		if (lastSortDir=="asc")
		{
			return "sortArrowUp.png";
		}
		else 
		{
			return "sortArrowDn.png";
		}
	}
	return "sortArrowNo.png";
}
/* This function is based on a multi-dimensional array sort algorithm that I found on the net.
   I added the ability to sort ascending or descending...
	 
	 Parameters:
     oArray (Array object) - the array to sort
		 element (integer) - the dimension to conduct the sort on
		 dir (string) - the sort direction: "asc" || "desc" */
function Sort(oArray, element, dir)
{
	for (var i=0; i<(oArray.length -1); i++)
	{
		for (var j=(i+1); j<oArray.length; j++)
		{
			if (dir == "asc")
			{
				if (oArray[j][element] < oArray[i][element])
				{
					var dummy = oArray[i];
					oArray[i] = oArray[j];
					oArray[j] = dummy;
				}
			}
			else
			{
				if (oArray[j][element] > oArray[i][element])
				{
					var dummy = oArray[i];
					oArray[i] = oArray[j];
					oArray[j] = dummy;
				}
			}
		}
	}
}

function OpenFile(url)
{
	var oWin;
	oWin = window.open(url, url, "location, scrollbars, resizable");
	
}



