// JavaScript Functions

/*--------------------------------------------------------------------------------------*\
 | Global variables defined for specific web browsers
/*--------------------------------------------------------------------------------------*/
var ns4    = document.layers;
var op5    = (navigator.userAgent.indexOf("Opera 5")!=-1) ||(navigator.userAgent.indexOf("Opera/5")!=-1);
var op6    = (navigator.userAgent.indexOf("Opera 6")!=-1) ||(navigator.userAgent.indexOf("Opera/6")!=-1);
var agt    = navigator.userAgent.toLowerCase();
var mac    = (agt.indexOf("mac")!=-1);
var ie     = (agt.indexOf("msie") != -1); 
var mac_ie = mac && ie;
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Get a TAG's handle identified by their ID name.
 |
 | Argument(s):	whichID		- Tag ID
/*--------------------------------------------------------------------------------------*/
function $(whichID)
{
	return document.getElementById(whichID);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Toggle a TAG ON/OFF
 |
 | If the given tag ID is visible, this function will make it invisible and vice-versa.
 |
 | Argument(s):	whichID		- Tag ID to toggle
/*--------------------------------------------------------------------------------------*/
function toggleDIV(whichID, optDisplay)
{
	var dv = $(whichID);
	
	if(dv != null)
	{
		if(dv.style.display == "none")
		{
			dv.style.display = (optDisplay == null ? "" : optDisplay);
			return true;
		}
		else
		{
			dv.style.display = "none";
			return false;
		}
	}
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Show or Hide a TAG
 |
 | Argument(s):	whichID		- Tag ID to show / hide
 |							showFlag	- Show flag (0 = hide, 1 = show)
/*--------------------------------------------------------------------------------------*/
function displayDIV(whichID, showFlag, optDisplay)
{
	var dv = $(whichID);
	
	if(dv != null)
	{
		if(showFlag == 0)
		{
			dv.style.display = "none";
			return false;
		}
		else
		{
			dv.style.display = (optDisplay == null ? "" : optDisplay);
			return true;
		}
	}
	else
	{
		return null;
	}
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Show or Hide a TAG
 |
 | Argument(s):	whichID		- ID of object
 |							isVisible	- true = set style visiblity to visible, false to hidden
/*--------------------------------------------------------------------------------------*/
function itemVis(whichID, isVisible)
{
	try
	{
		var dv = $(whichID);
		
		if(dv != null)
		{
			if(isVisible == true)
			{
				dv.style.visibility = "visible";
				return true;
			}
			else
			{
				dv.style.visibility = "hidden";
				return false;
			}
		}
		else
		{
			return null;
		}
	}
	catch(e)
	{ return null; }
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Load an XML Document
 |
 | Argument(s):	fname - file path & name of XML/XSL file to load
/*--------------------------------------------------------------------------------------*/
function loadXMLDoc(fname)
{
	var xmlDoc;
	// code for IE
	if (window.ActiveXObject)
  {
  	xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  }
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
  {
  	xmlDoc=document.implementation.createDocument("","",null);
  }
	else
  {
  	alert('Your browser cannot handle this script');
  }
  
	xmlDoc.async=false;
	xmlDoc.load(fname);
	
	return(xmlDoc);
}

/*--------------------------------------------------------------------------------------*\
 |Render XML to XSL in an HTML Element
 |
 | Argument(s):	 XMLFile - file path & name of XML data source file
 |               XSLFile - file path & name of XSL data source file
 |                    id - Element ID to show results in
/*--------------------------------------------------------------------------------------*/
function renderXSL(XMLFile, XSLFile, id)
{
	xml=loadXMLDoc(XMLFile);
	xsl=loadXMLDoc(XSLFile);
	
	// code for IE
	if (window.ActiveXObject)
  {
	  ex=xml.transformNode(xsl);
	  $(id).innerHTML = ex;
  }
	// code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument)
  {
	  xsltProcessor=new XSLTProcessor();
	  xsltProcessor.importStylesheet(xsl);
	  resultDocument = xsltProcessor.transformToFragment(xml,document);
	  $(id).appendChild(resultDocument);
  }
}


/*--------------------------------------------------------------------------------------*\
 |Convert XML to String
 |
 | Argument(s):	xml - string to convert
/*--------------------------------------------------------------------------------------*/
function XmlToString( xml )
{
	return new XMLSerializer().serializeToString(xml);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Replace content with a "Loading Progress" message
 |
 | Argument(s):	ContentDIV     - ID of DIV where the content to clear and show message
 |							WhereToNext    - URL of where the page is forwarding too
 |              LoadingMessage - Message to show while loading next page
/*--------------------------------------------------------------------------------------*/
function LoadingPageProgress(ContentDIV, WhereToNext, LoadingMessage)
{
	if($GE(ContentDIV) != null)
	{
		$GE(ContentDIV).innerHTML = "<div style=\"font-size: 16px; font-weight: bold; color: #0060B7; margin: 12px;\">" + LoadingMessage + "</div>";
	}
	
	window.location.href = "#";
	
	if(WhereToNext != "") window.location.href = WhereToNext;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Open Pop-Up Window
 |
 | Argument(s):	WhereTo  - URL to open
 |							Target   - Target location (default is "_blank")
 |              w, h     - Width & Height of window
 |              Params   - Additional window parameters
/*--------------------------------------------------------------------------------------*/
function PopupWin(WhereTo, Target, w, h, Params)
{
	Target = (Target != null && Target != "") ? Target : "_blank";
	w = (w != null && w > 0) ? w : 500;
	h = (h != null && h > 0) ? h : 450;
	Params = (Params != null && Params != "") ? "," + Params : "";
	
	win = window.open(WhereTo, Target, "width=" + w + ",height=" + h + Params);
	
	win.focus();
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Cookie Functions
/*--------------------------------------------------------------------------------------*/
function createCookie(name, value, days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) 
{
	createCookie(name,"",-1);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Format a number into Currency
 |
 | Argument(s):	num		- Number to convert
/*--------------------------------------------------------------------------------------*/
function formatCurrency(num) 
{
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)) num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	
	if(cents<10) cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Return a number to show n decimal places
 |
 | Argument(s):	num		- Number to convert
/*--------------------------------------------------------------------------------------*/
function formatFloat(num, decs) 
{
	num = num.toString().replace(/\$|\,/g,'');
	
	if(isNaN(num)) num = "0";
	
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/(10*decs)).toString();
	
	if(cents<10) cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	
	return (((sign)?'':'-') + num + '.' + cents);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Convert value from bytes to kilobytes, megabytes or gigabytes
 |
 | Argument(s):	f - Number to convert
/*--------------------------------------------------------------------------------------*/
function convertKb(f) 
{
  return (Math.round(f/1024*100000)/100000).toFixed(1);
}

function convertMb(f) 
{
	return (Math.round(f/1048576*100000)/100000).toFixed(1);
}

function convertGb(f) 
{
  return (Math.round(f/1073741824*100000)/100000).toFixed(1);
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Return the proper text for a specified file size
 |
 | Argument(s):	which - Number to convert
/*--------------------------------------------------------------------------------------*/
function styleFileSize(which)
{
	var floatSize = parseFloat(which);
	
	if(floatSize >= 1073741824)
		return convertGb(floatSize) + " Gb";
	else if(floatSize >= 1048576)
		return convertMb(floatSize) + " Mb";
	else if(floatSize >= 1024)
		return convertKb(floatSize) + " Kb";
	else
		return floatSize + " bytes";
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Toggle one image with another
 |
 | Argument(s):	whichNAME - Image tag name to toggle
 |							img1      - Image file name 1
 |              img2      - Image file name 2
/*--------------------------------------------------------------------------------------*/
function toggleIMG(whichNAME, img1, img2)
{
	if(whichNAME != null)
	{
		var path = getPath(whichNAME.src);
		var img  = getFilename(whichNAME.src);

		if(whichNAME.src == path + img1)
			whichNAME.src = path + img2;
		else
			whichNAME.src = path + img1;
	}
}
//---------------------------------------------------------------------------------------


/*--------------------------------------------------------------------------------------*\
 |Replace all from a given string with another string
 |
 | Argument(s):	string1	- [string to find]
 |							string2	- [string to replace string1 with]
/*--------------------------------------------------------------------------------------*/
String.prototype.replaceAll = function() 
{
	return this.split(arguments[0]).join(arguments[1])
};
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Set of general functions to return an element's width & height
/*--------------------------------------------------------------------------------------*/
function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

//---------------------------------------
// In these two functions the object must
// be visible before results are returned
//---------------------------------------
function getElementHeight(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.height;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) { 
			xPos = elem.style.pixelHeight;
		} else {
			xPos = elem.offsetHeight;
		}
		return xPos;
	} 
}

function getElementWidth(Elem) {
	if (ns4) {
		var elem = getObjNN4(document, Elem);
		return elem.clip.width;
	} else {
		if(document.getElementById) {
			var elem = document.getElementById(Elem);
		} else if (document.all){
			var elem = document.all[Elem];
		}
		if (op5) {
			xPos = elem.style.pixelWidth;
		} else {
			xPos = elem.offsetWidth;
		}
		return xPos;
	}
}
//---------------------------------------

function findXPos(EleID)
{
	var obj = $(EleID);
	
	if(obj != null)
	{
		var coords = new Array();
		
		coords = findPos(obj);
		
		return coords[0];
	}
	else
	{
		return 0;
	}
}

function findYPos(EleID)
{
	var obj = $(EleID);
	
	if(obj != null)
	{
		var coords = new Array();
		
		coords = findPos(obj);
		
		return coords[1];
	}
	else
	{
		return 0;
	}
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop  = obj.offsetTop;
		
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft
			curtop  += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function findPosX(obj)
{
  var curleft = 0;
  if(obj.offsetParent)
      while(1) 
      {
        curleft += obj.offsetLeft;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
      curleft += obj.x;
  return curleft;
}

function findPosY(obj)
{
  var curtop = 0;
  if(obj.offsetParent)
      while(1)
      {
        curtop += obj.offsetTop;
        if(!obj.offsetParent)
          break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
      curtop += obj.y;
  return curtop;
}

//------------------------------------
// Use:	var x = findPos($("mydiv")).X;
//			var y = findPos($("mydiv")).Y;
//------------------------------------
function findPos(obj)
{
	this.X = obj.offsetLeft;
	this.Y = obj.offsetTop;
	
	while(obj.offsetParent)
	{
		this.X = this.X+obj.offsetParent.offsetLeft;
		this.Y = this.Y+obj.offsetParent.offsetTop;
		
		if(obj == document.getElementsByTagName('body')[0]) 
		{
			break;
		}
		else
		{
			obj = obj.offsetParent;
		}
	}
	return this
}

function getWinDimLoc(whichDim)
{
	var winW;
	var winH;
	var winX;
	var winY;
	
	try
	{
		if (window.innerWidth)
		{
			winW = window.innerWidth;
			winH = window.innerHeight;
			winX = window.screenX;
			winY = window.screenY;
			
			//alert("FF: " + winW + "x" + winH + " | " + winX + "," + winY);
		}
		else
		{ 
			winW = document.body.clientWidth;
			winH = document.body.clientHeight;
			winX = window.screenLeft;
			winY = window.screenTop;
			
			//alert("IE: " + winW + "x" + winH + " | " + winX + "," + winY);
		}
	}
	catch(e) { }
	
	if(whichDim == "w") return winW;
	if(whichDim == "h") return winH;
	if(whichDim == "x") return winX;
	if(whichDim == "y") return winY;
	
	return winW + "," + winH + "," + winX + "," + winY;
}

function getScrollOffsetX()
{
	var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
	
	return document.all ? iebody.scrollLeft : pageXOffset;
}

function getScrollOffsetY()
{
	var iebody = (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
	
	return document.all ? iebody.scrollTop  : pageYOffset;
}



/*---------------------------------------------------------------*\
| Force the size of an element to an even width or height or both |
\*---------------------------------------------------------------*/
function MakeEvenSize(WhichID, WorH)
{
	if(WorH.toLowerCase() == "h" || WorH == "")
	{
		var tHeight = getElementHeight(WhichID);
		
		if (tHeight % 2)
			document.getElementById(WhichID).style.height = tHeight + 1;
	}
	
	if(WorH.toLowerCase() == "w" || WorH == "")
	{
		var tWidth = getElementWidth(WhichID);
		
		if (tWidth % 2)
			document.getElementById(WhichID).style.width = tWidth + 1;
	}
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Clear a list a given listbox
 |
 | Argument(s):	lb - Listbox to clear
/*--------------------------------------------------------------------------------------*/
function clearListbox(lb)
{
  for (var i=lb.options.length-1; i>=0; i--)
  {
    lb.options[i] = null;
  }
  
  lb.selectedIndex = -1;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return only the path from a URL
 |
 | Argument(s):	whichURL - URL to extract
/*--------------------------------------------------------------------------------------*/
function getPath(whichURL)
{
	if(trim(whichURL) != "" && whichURL != null)
	{
		var aa = whichURL.lastIndexOf("/");
		
		if(aa < 0)	// no slash was found
		{
			aa = whichURL.lastIndexOf("\\");
			
			if(aa < 0)
				if(whichURL.indexOf(".") < 0)
					return trim(whichURL);			// Nothing but a single word was found
				else
					return "";									// All that was found was a file with an extention
			else
				return trim(whichURL.substr(0, aa) + "/");
		}
		else
		{
			return trim(whichURL.substr(0, aa) + "/");
		}
	}
	else
	{
		return "";
	}
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return only the file name from a URL
 |
 | Argument(s):	whichURL - URL to extract file name
/*--------------------------------------------------------------------------------------*/
function getFilename(whichURL)
{
	whichURL = trim(whichURL);
	
	if(whichURL != "" && whichURL != null)
	{
		var aa = whichURL.lastIndexOf("/");
		
		if(aa < 0)	// no slash was found
		{
			aa = whichURL.lastIndexOf("\\");
			
			if(aa < 0)
				if(whichURL.indexOf(".") > -1)
					return trim(whichURL);	// No slash to be found so just return string
				else
					return "";							// No extension was found so return nothing
			else
				return trim(whichURL.substr(aa + 1, whichURL.length));
		}
		else
		{
			return trim(whichURL.substr(aa + 1, whichURL.length));
		}
	}
	else
	{
		return trim(whichURL);
	}
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return only the file extension from a filename
 |
 | Argument(s):	whichFile - file name with extension
/*--------------------------------------------------------------------------------------*/
function getFileExtension(whichFile)
{
	try
	{	return trim(whichFile.substr(whichFile.lastIndexOf(".") + 1).toLowerCase()); }
	catch(e)
	{ return ""; }
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Test to see if string1 is found in the given array.  Test is not strict (caseless).
 |
 | Argument(s):	strArray - string array to check in
 |              strTest  - string to look for
/*--------------------------------------------------------------------------------------*/
function isStringInArray(strArray, strTest)
{
	return (new RegExp('^(' + strArray.join('|').toLowerCase() + ')$').test(strTest.toLowerCase()));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Function: trim ( string )
 |
 | Purpose: Trim leading and trailing spaces off a string and return
 |
 | Args: string - string to trim
/*--------------------------------------------------------------------------------------*/
function trim(what) {
	var aa = what;
	
	// Trim Leading Spaces
	while(aa.charAt(0) == ' ') {
		aa = aa.substring(1, aa.length);
	}
	
	// Trim Trailing Spaces
	while(aa.charAt(aa.length-1) == ' ') {
		aa = aa.substring(0, aa.length-1);
	}
	
	return aa;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Return the Decimal value of a given Hex number
 |
 | Argument(s):	Number - integer value to convert
/*--------------------------------------------------------------------------------------*/
function hexToDec(hexNum) 
{ 
	return parseInt(hexNum,16);
} 
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Return the HEX value of a given number (version 1)
 |
 | Argument(s):	Number - integer value to convert
/*--------------------------------------------------------------------------------------*/
function decToHex(d) 
{
	var hD="0123456789ABCDEF";
	var h = hD.substr(d&15,1);

	while(d>15)
	{
		d>>=4; 
		h = hD.substr(d&15, 1) + h;
	}
	return h;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Return the HEX value of a given number (version 2)
 |
 | Argument(s):	Number - integer value to convert
/*--------------------------------------------------------------------------------------*/
function decToHex2(Number) 
{
	var String = "";
	
	if (dec > 15) 
	{
		hexString = decToHex(Math.floor(dec / 16));
	}
	var hexDigit = dec - 16 * (Math.floor(dec / 16)); 
	
	if (hexDigit > 9) 
	{
		hexDigit = String.fromCharCode(hexDigit + 55);
	}
	hexString = hexString + hexDigit;
	
	return hexString;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Return the decimal value for the Red, Green or Blue part of a given Hex color
 |
 | Argument(s):	hexVal - 6-digit hexidecimal value
/*--------------------------------------------------------------------------------------*/
function getRed(hexVal)
{
	if(trim(hexVal).length > 6)	// Check for '#' chr
		hexVal = hexVal.substr(1, 7);
	
	return hexToDec(hexVal.substr(0,2));
}

function getGreen(hexVal)
{
	if(trim(hexVal).length > 6)	// Check for '#' chr
		hexVal = hexVal.substr(1, 7);
	
	return hexToDec(hexVal.substr(2,2));
}

function getBlue(hexVal)
{
	if(trim(hexVal).length > 6)	// Check for '#' chr
		hexVal = hexVal.substr(1, 7);
	
	return hexToDec(hexVal.substr(4,2));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Search for a target string and replace it with another
 |
 | Argument(s):	holder      - original string
 |							searchFor   - string to find
 |							replacement - replacement for search string
/*--------------------------------------------------------------------------------------*/
function searchAndReplace(holder, searchfor, replacement) 
{
	temparray = holder.split(searchfor);
	holder = temparray.join(replacement);
	
	return (holder);
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Add URL to client's favorites
 |
 | Argument(s):	urlAddress - Address string of the URL to bookmark
 |							pageName   - Name of the page to bookmark
 | Returns:     true/false - true if client's browser supports this function
/*--------------------------------------------------------------------------------------*/
function addToFavorites(url, title)
{
	if (window.sidebar)
	{	// FIREFOX
		window.sidebar.addPanel(title, url, "");
	}
	else if(window.opera && window.print)
	{ // OPERA
		var elem = document.createElement('a');
		elem.setAttribute('href', url);
		elem.setAttribute('title', title);
		elem.setAttribute('rel', 'sidebar');
		elem.click();
	} 
	else if(document.all)
	{	// IE
		window.external.AddFavorite(url, title);
	}
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return the current date in the format: 2006/01/01
 |
 | Argument(s):	divider - preferred divider character (default is '/')
/*--------------------------------------------------------------------------------------*/
function getDate(divider, isYearFirst)
{
	var Today = new Date();
	
	if(divider == null) divider = "";
	
	if(isYearFirst == true || isYearFirst == null)
		return (Today.getFullYear() + divider + addZeros(Today.getMonth()+1, 2) + divider + addZeros(Today.getDate(), 2));
	else
		return (addZeros(Today.getMonth()+1, 2) + divider + addZeros(Today.getDate() + divider + Today.getFullYear(), 2));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return the number of days until a specified expiration date
 |
 | Argument(s):	Expires - string-formatted date (ie. "October 13, 2007")
 | Returns:     The number of days until today's date meets the expiration date
 |              > 0 : the expiration date hasn't been reached yet
 |              = 0 : the expiration date and today's date are the same
 |              < 0 : the expiration date has past
/*--------------------------------------------------------------------------------------*/
function CheckExpirationDate(Expires)
{
	var endDate    = new Date(Expires);
	var today      = new Date();
	var difference = 0;
	
	difference = endDate - today;
	
	return Math.round(difference/(1000*60*60*24));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Return the current time in the format: 01:01:01
 |
 | Argument(s):	none
/*--------------------------------------------------------------------------------------*/
function getTime() 
{
	var Time = new Date();
	
	return (addZeros(Time.getHours(), 2) + ":" + addZeros(Time.getMinutes(), 2) + ":" + addZeros(Time.getSeconds(), 2));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Pad a numeric value with zeros - such as 1 -> 001
 |
 | Argument(s):	val - value to add zeros to
 |              num - number of zeros to pad (if count=2 & value = 6, returned is 06)
/*--------------------------------------------------------------------------------------*/
function addZeros(val, num) 
{
	var zeros  = "";
	
	for(var aa = 1; aa <= (num - String(val).length); aa++) {
		zeros += "0";
	}
	return zeros + String(val);
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Pad a string with a character - such as "1" -> "001" or "A" -> "  A"
 |
 | Argument(s):	str - string value to add characters to
 |              num - number of zeros to pad (if count=2 & value = 6, returned is 06)
 |              chr - character to pad with
/*--------------------------------------------------------------------------------------*/
function padStr(str, num, padCHR)
{
	var chrs  = "";
	
	padCHR = (padCHR == "" || padCHR == " ") ? "&nbsp;" : padCHR;
	
	for(var aa = 1; aa <= (num - str.length); aa++) {
		chrs += padCHR;
	}
	return chrs + String(str);
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Validates an Email Address
 |
 | Argument(s):	email - (str) Email address to validate
 | Returns:     true (was valid) / false (was not valid)
/*--------------------------------------------------------------------------------------*/
function validEmail(email)
{
            
	//10-6-08 - changed to allow 4 character domain 
	//if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(email))
	{
		return (true);
	} 
	
	return (false);
}
/*--------------------------------------------------------------------------------------*\


/*--------------------------------------------------------------------------------------*\
 |Returns the total number of items in a <select> list
 |
 | Argument(s):	whichList - handle of list tag
/*--------------------------------------------------------------------------------------*/
function getTotalListItems(whichList)
{
	for(aa = 0; aa < 10000; aa++)
	{
		if(whichList.options[aa] == null) return aa;
	}
	
	return aa;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 | Data Bind Listbox
 |
 | Argument(s):	ddl      - listbox to bind
 |              aryText  - array of elements to bind as the text
 |              aryValue - array of elements to bind as the values
/*--------------------------------------------------------------------------------------*/

function bindListbox(ddl, aryText, aryValue)
{
	for(var i = 0; i < aryText.length; i++)
		ddl.options.add(new Option(aryText[i], aryValue[i]));
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Clear all items from a drop-down menu or listbox
 |
 | Argument(s):	objSelect - drop-down or listbox object
 |              iniText   - optional new initial first text
 |              iniVal    - optional new initial first value
/*--------------------------------------------------------------------------------------*/
function clearDD(objSelect, iniText, iniVal)
{
	for (var i = (objSelect.options.length-1); i >= 0; i--)
		objSelect.options[i] = null;
	
	if(iniText != "" && iniText != null)
		objSelect.options[0] = new Option(iniText, iniVal); //If you want to display some new value
}

/*--------------------------------------------------------------------------------------*\
 |Delete an item from a listbox or drop-down menu
 |
 | Argument(s):	whichDropDown - handle of list tag
 |              whichItem     - list index of item to remove
/*--------------------------------------------------------------------------------------*/
function deleteFromDropDown(whichDropDown, whichItem)
{
	for(i = whichItem; i < (whichDropDown.length - 1); i++)
	{
		whichDropDown.options[i].text  = whichDropDown.options[i + 1].text;
		whichDropDown.options[i].value = whichDropDown.options[i + 1].value;
	}
	
	whichDropDown.length = whichDropDown.length - 1;
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |Moves an item in a listbox or drop-down Up or Down
 |
 | Argument(s):	whichList - handle of list tag
 |              whichItem - which item to move (selected index)
 |              whichDir  - which way to move it (0 - up, 1 - down)
/*--------------------------------------------------------------------------------------*/
function moveListItem(whichList, whichDir)
{
	var whichItem = whichList.selectedIndex;
	
	if(whichList.options.length > 0)
	{
		if(whichDir == 0)		// move up
		{
			if(whichItem > 0)	// item is not at the top of the list already
			{
				//moveUp(whichList);
				move(whichList, true);
			}
		}
		else								// move down
		{
			if(whichItem < (whichList.length-1))	// item is not at the bottom of the list already
			{
				//moveDown(whichList);
				move(whichList, false);
			}
		}
	}
}

	/*------------------------------------------------------------------------------------*/
	/* moveListItem() Supporting Function
	/*------------------------------------------------------------------------------------*/
	function move(el, bDir) 
	{
		var idx = el.selectedIndex
	
		if (idx==-1) 
		{
			alert("You must first select the item to reorder.");
		}
		else 
		{
			var nxidx = idx+( bDir? -1 : 1)
		
			if (nxidx<0) nxidx=el.length-1
			if (nxidx>=el.length) nxidx=0
		
			var oldVal = el[idx].value
			var oldText = el[idx].text
		
			el[idx].value = el[nxidx].value
			el[idx].text = el[nxidx].text
			el[nxidx].value = oldVal
			el[nxidx].text = oldText
			el.selectedIndex = nxidx
		}
	}
	/*------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------*\
 |[CLASS] Returns a control value or type
 |
 |   Argument(s): frm		- the form control NAME
 |                delim	- an optional delimiter used for returning multiple values
 |
 | Usage Example: var ctl = new formElement("controlName"[,"delimiter"]).getValue();/getType();
 |                
/*--------------------------------------------------------------------------------------*/
function formElement()
{
  var frm = formElement.arguments[0];
  var delim = formElement.arguments[1];
  delim = (delim==undefined) ? ',' : delim;
  
  this.getType = function ()
  {
    var ElementType = document.getElementsByName(frm)[0].tagName.toLowerCase();
		
    if(ElementType=='input'){
      ElementType = document.getElementsByName(frm)[0].getAttribute("type").toLowerCase();
    }
    if(ElementType=='select'){
      if(document.getElementsByName(frm)[0].getAttribute("multiple")==undefined){
        ElementType='select-one';
      }else{
        ElementType=document.getElementsByName(frm)[0].getAttribute("multiple").toString().toLowerCase();
        ElementType=(ElementType=='false')?'select-one':'select-multiple';
      }
    }
    if(ElementType=='checkbox') ElementType=ElementType+((document.getElementsByName(frm).length > 1)?'list':'');
    return ElementType;
  }

  this.getValue =  function ()
  {
    var ElementType = this.getType();
    var Elements = document.getElementsByName(frm);
    
    switch(ElementType)
    {
      case "text":
        return Elements[0].value;
        break;
      
      case "hidden":
        return Elements[0].value;
        break;
        
      case "radio":
        for(var x=0;x< Elements.length;x++){
          if(Elements[x].checked){return Elements[x].value;}
        }
        break;
      
      case "checkbox":
        return (Elements[0].checked) ? Elements[0].value : "";
        break;
      
      case "checkboxlist":
        var ary = new Array();
        for(var b=0;b< Elements.length;b++){
          if(Elements[b].checked){
            ary[ary.length]=Elements[b].value;
          }
        }
        return ary.join(delim);
        break;
      
      case "select-one":
        return Elements[0].value;
        break;
      
      case "select-multiple":
        var ary = new Array();
        for(var a=0;a<Elements[0].options.length;a++){
          if(Elements[0].options[a].selected){
            ary[ary.length]=Elements[0].options[a].value;
          }
        }
        return ary.join(delim);
        break;
      
      case "textarea":
        return Elements[0].value;
        break;
    }
  }
}
/*--------------------------------------------------------------------------------------*/


/*--------------------------------------------------------------------------------------
 | Get detailed file format
 |   Argument(s): ext        - (string)     file name extension
 |                getDetails - (true/false) return detailed file type format
 |
 |   Returns: getDetails = true  > detailed file description (ex: "Image (jpg)")
 |            getDetails = false > anything <> web image format an icon image filename 
 |                                 is returned, otherwise and empty string is returned
/*--------------------------------------------------------------------------------------*/
function getDefaultFile(ext, getDetails)
{
	switch(ext)
	{
		case "gif":
		case "jpg":
		case "jpeg":
		case "png":
		case "bmp":
		case "ico":
			if(getDetails == true)
				return "Image (" + ext + ")";
			else
				return "";
			break;
		
		case "tif":
		case "tiff":
		case "eps":
		case "ai":
			if(getDetails == true)
				return "Image (" + ext + ")";
			else
				return "icon_ImageEditL.gif";
			break;
			
		case "cur":
		case "ani":
			if(getDetails == true)
				return "Windows Media (" + ext + ")";
			else
				return "icon_Windows.gif";
			break;
		
		case "swf":
			if(getDetails == true)
				return "Flash Program";
			else
				return "icon_FlashProgram.gif";
			break;
			
		case "fla":
			if(getDetails == true)
				return "Flash Source";
			else
				return "icon_FlashSource.gif";
			break;
		
		case "wmv":
		case "mpeg":
		case "mpg":
		case "mov":
		case "avi":
			if(getDetails == true)
				return "Video (" + ext + ")";
			else
				return "icon_Movie.gif";
			break;
		
		case "mp3":
		case "wav":
			if(getDetails == true)
				return "Audio (" + ext + ")";
			else
				return "icon_Sound.gif";
			break;
		
		case "zip":
			if(getDetails == true)
				return "ZIP (" + ext + ")";
			else
				return "icon_ZIPFile.gif";
			break;
			
		case "psd":
			if(getDetails == true)
				return "Photoshop";
			else
				return "icon_Photoshop.gif";
			break;
		
		case "pdf":
			if (getDetails == true)
				return "Adobe PDF";
			else
				return "icon_PDF.gif";
			break;
		
		case "xml":
			if(getDetails == true)
				return "Extensible Markup Language (XML)";
			else
				return "icon_XML.gif";
			break;
			
		case "txt":
			if(getDetails == true)
				return "Text Document";
			else
				return "icon_TextDocument.gif";
			break;
			
		case "doc":
			if(getDetails == true)
				return "Word Document";
			else
				return "icon_WordDocument.gif";
			break;
			
		case "xls":
			if(getDetails == true)
				return "Excel Spreadsheet";
			else
				return "icon_ExcelDocument.gif";
			break;
			
		case "pps":
			if(getDetails == true)
				return "PowerPoint Presentation";
			else
				return "icon_PowerPoint.gif";
			break;
		
		default:
			if(getDetails == true)
				return ext.toUpperCase() + " File";
			else
				return "icon_MultiFile.gif";
			break;
	}
}

/*--------------------------------------------------------------------------------------
 | Preload Image Class
 |--------------------------------------------------------------------------------------
 | Using the Class:
 |   Syntax Example:
 |
 |     ____ErrorTagCode = "Image could not be loaded!";
 |     ____ErrorTagID   = "img_area";
 |     ____ImageArray[____ImageArray.length > 0 ? ____ImageArray.length-1 : 0] = "image.gif";
 |
 |     ip = new ImagePreloader(____ImageArray, onPreload);
 |
 |     <div id="img_area"></div>
/*--------------------------------------------------------------------------------------*/
var ____ip           = null;
var ____ImageArray   = new Array();
var ____ErrorTagID   = "";
var ____ErrorTagCode = "";

function onPreload(aImages, nImages)
{
	var eti;
	
	if(nImages != aImages.length)
	{
		eti = $("____ErrorTagID");
		
		if(eti != null)
			eti.innerHTML = ____ErrorTagCode;
	}
}

function ImagePreloader(images, callback)
{
   // store the call-back
   this.callback = callback;

   // initialize internal state.
   this.nLoaded = 0;
   this.nProcessed = 0;
   this.aImages = new Array;

   // record the number of images.
   this.nImages = images.length;

   // for each image, call preload()
   for ( var i = 0; i < images.length; i++ ) 
      this.preload(images[i]);
}

	ImagePreloader.prototype.preload = function(image)
	{
		 // create new Image object and add to array
		 var oImage = new Image;

		 this.aImages.push(oImage);

		 // set up event handlers for the Image object
		 oImage.onload = ImagePreloader.prototype.onload;
		 oImage.onerror = ImagePreloader.prototype.onerror;
		 oImage.onabort = ImagePreloader.prototype.onabort;

		 // assign pointer back to this.
		 oImage.oImagePreloader = this;
		 oImage.bLoaded = false;

		 // assign the .src property of the Image object
		 oImage.src = image;
	}

	ImagePreloader.prototype.onComplete = function()
	{
		 this.nProcessed++;

		 if ( this.nProcessed == this.nImages )
   		this.callback(this.aImages, this.nLoaded);
	}

	ImagePreloader.prototype.onload = function()
	{
		 this.bLoaded = true;
		 this.oImagePreloader.nLoaded++;
		 this.oImagePreloader.onComplete();
	}

	ImagePreloader.prototype.onerror = function()
	{
		 this.bError = true;
		 this.oImagePreloader.onComplete();
	}

	ImagePreloader.prototype.onabort = function()
	{
		 this.bAbort = true;
		 this.oImagePreloader.onComplete();
	}
/*--------------------------------------------------------------------------------------*/
	

/*--------------------------------------------------------------------------------------
 | Get AJAX XMLHttp Object
 |   Argument(s): none
 |
 |   Returns: returns null if AJAX is not supported on client's browser, otherwise
 |            returns the XMLHTTP object handle
/*--------------------------------------------------------------------------------------*/
function GetXmlHttpObject()
{
	var xmlHttp = null;

	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); }
    catch (e)
		{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	}
  
  return xmlHttp;
}


/*--------------------------------------------------------------------------------------
 | A useful set of functions by HTMLSource: 
 | http://www.yourhtmlsource.com/javascript/ajax.html
/*--------------------------------------------------------------------------------------*/

// Cross-browser event handling, by Scott Andrew

function addEvent(element, eventType, lamdaFunction, useCapture) 
{
  if (element.addEventListener) 
  {
    element.addEventListener(eventType, lamdaFunction, useCapture);
    return true;
  } 
  else if (element.attachEvent) 
  {
    var r = element.attachEvent('on' + eventType, lamdaFunction);
    return r;
  }
  else
  {
		return false;
  }
}

// Kills an event's propagation and default action

function knackerEvent(eventObject) 
{
	if (eventObject && eventObject.stopPropagation)
		eventObject.stopPropagation();
	
	if (window.event && window.event.cancelBubble ) 
		window.event.cancelBubble = true;
	
	if (eventObject && eventObject.preventDefault)
		eventObject.preventDefault();
	
	if (window.event)
		window.event.returnValue = false;
}

// Safari doesn't support canceling events in the standard way, so we must
// hard-code a return of false for it to work.

function cancelEventSafari()
{
	return false;        
}

// Cross-browser style extraction, from the JavaScript & DHTML Cookbook
// <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>

function getElementStyle(elementID, CssStyleProperty) 
{
	var element = document.getElementById(elementID);
	
	if (element.currentStyle) 
	{
		return element.currentStyle[toCamelCase(CssStyleProperty)];
	} 
	else if (window.getComputedStyle) 
	{
		var compStyle = window.getComputedStyle(element, '');
		return compStyle.getPropertyValue(CssStyleProperty);
	} 
	else 
	{
		return '';
	}
}

// CamelCases CSS property names. Useful in conjunction with 'getElementStyle()'
// From <http://dhtmlkitchen.com/learn/js/setstyle/index4.jsp>

function toCamelCase(CssProperty) 
{
	var stringArray = CssProperty.toLowerCase().split('-');

	if (stringArray.length == 1) 
	{
		return stringArray[0];
	}
	
	var ret = (CssProperty.indexOf("-") == 0) ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1) : stringArray[0];
	
	for (var i = 1; i < stringArray.length; i++) 
	{
		var s = stringArray[i];
		ret += s.charAt(0).toUpperCase() + s.substring(1);
	}
	
	return ret;
}

// Disables all 'test' links, that point to the href '#', by Ross Shannon

function disableTestLinks() 
{
	var pageLinks = document.getElementsByTagName('a');
	
	for (var i=0; i<pageLinks.length; i++) 
	{
		if (pageLinks[i].href.match(/[^#]#$/))
			addEvent(pageLinks[i], 'click', knackerEvent, false);
	}
}
/*--------------------------------------------------------------------------------------*/

