// JavaScript Document

/** ****************************************************
 *
 *	File is designed to make anchor tags W3C compliant
 *  by not using the target attribute in anchor tags, and
 *	no longer opening non-xhtml files in new windows. 
 *  
 *  Since opening large non-xhtml files in the current window
 *	may prove problematic for slow connections, functions
 *	that will add file sizes to an anchor tag's title attribute
 *	are provided.
 *
 *	This file is designed for use on Cob (intranet).
 *
 *	EXAMPLE USAGE:
 *  	place the following tag in the <HEAD>
 *
 *		<script type="text/javascript" src="/departments/Volunteer2/scripts.js"></script>
 *
 * **************************************************** */
 
 
 /*  Script adds title attributes to local non-xhtml file links.
	
	The script scans
	the xhtml for anchor tags that have an href value containing '' or
	''; (to indicate a local file).
	
	Each found anchor tag has an xmlHttpRequest object attached as a 
	property. The request object retrieves the request pdf file size.
	
	The response is then parsed and added to the anchor tags title
	property.
	
*/

jmHTTP = new Object();

jmHTTP = {
	
	READY_STATE_UNINITIALIZED : 0,
	READY_STATE_LOADING : 1,
	READY_STATE_LOADED : 2,
	READY_STATE_INTERACTIVE : 3,
	READY_STATE_COMPLETE : 4,

	ERROR_FLAG : 'Server Error ',

/** ************************************************************
 *
 *	Function is designed to create and retrieve an HTTP request/response from
 *	the server.
 *
 *		url - is the relative path to the file on the server
 *
 *		HTTPMethod - should be 'GET', 'POST', or 'HEAD'
 *
 *		headers - is two dimensional array of HTTP header name-value pairs as strings
 *			EX:  [ ['Content-Type', 'text/html'] ]
 *
 *		asynchronous  - is true for asynchronous or false for synchronous communication
 *
 *		onReadyStateHandler - is the onreadystatechange event handler function. This
 *			should be defined for each application.
 *
 *		params - usually a list of name value pairs for a POST
 *
 *
 */

	sendRequest : function(url, headers, HttpMethod, asynchronous, params) {
		var request = null;
		var name = '';
		var value = '';
		
		request = getXMLHTTPRequest();
		
		if(request){
			request.open(HttpMethod, url, asynchronous, '', '');
			request.onreadystatechange = onreadystateHandler;
			
			if(headers) {
				for(var i = 0; i < headers.length; i++){
					name = headers[i][0];
					value = headers[i][1];
					request.setRequestHeader(name, value);
				}
			}
			request.send(params);
		}
		return(request);
		
		
		/**
		 *	This is the onclick handler from the local page
		 *
		 */
		function onreadystateHandler()  {
			var contentLength = CobReq.TITLE_ERROR;
			if (request.readyState == jmHTTP.READY_STATE_COMPLETE){
				if(request.status == 200) {
					//alert('in request.status == 2 request.backPtr.id is: ' + request.backPtr.id);
					contentLength = request.getResponseHeader('Content-Length');
				}
				else contentLength = 'Status: ' + request.status;
				//alert('in onreadystateHandler contentLength is: ' + contentLength + '\nrequest.backPtr is: ' + request.backPtr);
				CobReq.setTitle(contentLength, request.backPtr);
				request = null;
			}
		}//end func onreadystateHandler
		
		
		
		function getXMLHTTPRequest(){
			var newRequest = null;
			if(window.XMLHttpRequest) newRequest = new XMLHttpRequest() //W3C
			
			else if(window.ActiveXObject) {
				newRequest = new ActiveXObject('Msxml2.XMLHTTP'); //new IE
				if(!newRequest) newRequest = new ActiveXObject('Microsoft.XMLHTTP'); //old IE
				alert('in inner getXMLHTTPRequest newRequest is: ' + newRequest);
			}
			alert('in getXMLHTTPRequest newRequest is: ' + newRequest);
			return newRequest;
		}//end getXMLHTTPRequest
	}//end sendRequest
	
} //end jmHTTP








/** ***************************************************************************
 *	This script sets the title attribute of anchor tags that have an 
 *  href attribute pointing to a local PDF file.
 *
 *	Each found anchor tag has an XMLHttpRequest Object attached to it.
 *	The request object's callback function assigns the anchor's title
 *	attribute value to the server's response, if all goes well
 *	the file size.
 * ************************************************************************** */
 
 CobReq = new Object();
 
 CobReq = {
	 LOCAL_FILE 	: '/cob/',
	 TITLE_OFFSITE	: '',
	 TITLE_ERROR	: 'Server error. File size unavailable.',
	 TITLE_PREFIX 	: 'File size is:  ',
	 NEW_LINE   	: '\n',
	 TITLE_POSTFIX	: ' KB',
	 
	 
	 setTitle	: function(serverResponse, currentAnchor) {
		
		var newTitle = '';
		if(currentAnchor.title) newTitle = currentAnchor.title;
		if(newTitle) newTitle += CobReq.NEW_LINE;
		
		//alert('in setTitle serverResponse is: ' + serverResponse);
		
		var newText = Math.round(parseInt(serverResponse)/1000).toString();
		
		if(newText != 'NaN') {
			newText = parseFileSize(newText);
			newTitle += CobReq.TITLE_PREFIX + newText + CobReq.TITLE_POSTFIX;
		} //end if newText is a number
		else {
			newTitle += CobReq.TITLE_OFFSITE;
		}
		
		currentAnchor.title = newTitle; 
		
		
	   /** ********************************************************************
		*	function adds commas to whole numbers > 999
		*	
		*	input:
	    *		fileSize:  the string representation of a whole number.
		*		
		*	output:
		*		the string representation of fileSize in standard notation
		*		
		*	NOTES:
		*		to add commas the input string is reversed, commas added to
		*		the reversed string, and finally the reversed string is
		*		reversed back to the original order with the added commas
		*		
		*********************************************************************** */
		function parseFileSize(fileSize) {
			var standardNotation = fileSize;
			var reversedfileSize = '';
			
			if(fileSize.length > 3){
				standardNotation = '';
				for(var i = fileSize.length; i > -1; i--) reversedfileSize += fileSize.charAt(i);
				reversedfileSize = reversedfileSize.replace(/(\d\d\d)(?=\d)/g, '$1,');
				for(i = reversedfileSize.length; i > -1; i--) standardNotation += reversedfileSize.charAt(i);
			}//end if fileSize > 3
			return standardNotation;
		}//end func parseFileSize
		
	 },//end func setTitle
	 
	 
	 /* 
	 	This function recursively checks through the rootElem
		child nodes. When a child node is found that fits the
		search criteria (an anchor tag pointing to a local non-
		xhtml file) an XHR (XMLHTTPRequest) object is instantiated
		and opened.
		
		INPUT:	
			rootElem:  The id attribute value of the docment element
				that is the root for the search.
				
		OUTPUT:
			there is no output but each selected anchor tag has an
			XHR added as a property. This object will provide output.
	*/
	 traverse	: function(rootElem) {
		 
		var child = null;
		var hrefValue = '';
		
		for(var i = 0; i < rootElem.childNodes.length; i++){
			child = rootElem.childNodes[i];
			if (child.nodeType == 1) {
				if (child.nodeName.toLowerCase() == 'a' && child.href){
					
					if( child.href.search(this.LOCAL_FILE) > 0 ){
						if ( 
							child.href.search('.pdf') > 0 || 
							child.href.search('.doc') > 0 ||
							child.href.search('.xls') > 0 ||
							child.href.search('.txt') > 0 ||
							child.href.search('.dwg') > 0 
							) {	
							
							child.serverRequest = jmHTTP.sendRequest(child.href,
													[ ['Content-Type', '*/*'] ], 
													'HEAD', true, null);
							
							if (child.serverRequest) child.serverRequest.backPtr = child;
							
						}//end if correct file type
						
					} //end if our site
					else CobReq.setTitle(CobReq.TITLE_OFFSITE, child);	
					
				}// end if nodeName is 'a'
				else CobReq.traverse(child);
			}// end if nodeType is 1
		}//end for	 
	 }, //end func traverse
	 
	 
	 /** ********************************************************************
	  *	  This function initializes the file size object for the
	  *		Cob website.
	  *
	  *	  NOTE:
	  *      Only the "standard" content containing DOM elements will
	  *		 be searched for local documents.
	  *********************************************************************** */
	 
	 init	:	function() {
		 
		 var domRoot = document.getElementById('container');
		 
		 if (domRoot) CobReq.traverse(domRoot);
	 }
	 
 }//end CobReq namespace
 


/** ***************************************************************************
 *
 *	Name space object for using the rel attribute to replace the
 *	target attribute in anchor tags.
 *
 * ************************************************************************** */

CobFauxTarget = new Object();

CobFauxTarget = {
	NEWWIND : 'newwindow',

	/** 
	   This function inspects all anchor tags in the document for the
	   rel attribute. If the rel attribute value is a variation on NEWWIND
	   the link will open in a new window or tab.
	   
	*/
	newWindowOpener	:	function() {
		
		if(document.getElementsByTagName){
			var anchors = document.getElementsByTagName('a');
			var areas = document.getElementsByTagName('area');
			var anchorElem = null;
			setTargets(anchors);
			setTargets(areas);
			/*
			for(var i = 0; i < anchors.length; i++) {
				anchorElem = anchors[i];
				if(anchorElem.href &&
					anchorElem.rel == 'newwindow') {
					anchorElem.target = '_blank';
				}//end if anchorElem.rel
			}//end for
			*/
		}//end if getElementsByTagName
		
		
		function setTargets(elementsArray) {
			var elem = null;
			for(var i = 0; i < elementsArray.length; i++){
				elem = elementsArray[i];
				if(elem.href && elem.rel == 'newwindow') elem.target = '_blank';
			}
		} //end func setTargets
			
	}//end func newWindowOpener
	
} //end CobFauxTarget
 
 
 
 
 
/** **************************************************************
 *
 *	Name space object for running multiple functions on a
 *	window onload event.
 *
 * *************************************************************** */
 
CobAnchors = new Object();

CobAnchors = {

	init :	function() {
		//alert('in CobAnchors.init()');
		CobFauxTarget.newWindowOpener();
		//FileSize.init();
	} // end func init
}// end CobAnchors

 
 
 
 
 
 /*  ***************************************
	  Code runs when file is loaded.
	  
	  Adds an onload event handler to the window object
	  that will not overwrite other window onload
	  handlers.
 * ****************************************** */
 
 
 if (window.addEventListener) window.addEventListener('load', CobAnchors.init , false);
 else if(window.attachEvent) window.attachEvent('onload', CobAnchors.init);
