function addEvent(elm, evType, fn, useCapture)
// elm        - element on which to add the event
// evType     - event to watch for
// fn         - function to attach to the event
// useCapture - which
// e.g. addEvent(window, "load", sortables_init);
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
} 

function scrollToTop(container) {
	// scrolls an object with scrollbars (e.g. a div with fixed height and overflow: auto) to the top
	if (document.getElementById && document.getElementById(container)) {
		document.getElementById(container).scrollTop=0;
	}
}


function popitup(popurl,thewidth,theheight) {
  // The popitup function pops a page up up a new window.
  // It's called from the <a> element.
  // It passes the URL, width, and height as variables.
  winstring="width="+thewidth+",height="+theheight+",top=50,left=50,scrollbars,resizable"
  winpops=window.open(popurl,"window2",winstring)
}

function popitup_fullwin(popurl) {
  // The popitup function pops a page up up a new window.
  // It's called from the <a> element.
  // It passes the URL, width, and height as variables.
  winstring="toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,left = 0,top = 0"
  winpops=window.open(popurl,"window2",winstring)
}

function popitup_passback(popurl,thewidth,theheight) {
  // The popitup function pops a page up up a new window.
  // It's called from the <a> element.
  // It passes the URL, width, and height as variables.
  winstring="width="+thewidth+",height="+theheight+",top=50,left=50,scrollbars,resizable"
  winpops=window.open(popurl,"",winstring)
}



function Mid(str, start, len) {
  if (start < 0 || len < 0) return "";
  var iEnd, iLen = String(str).length;
  if (start + len > iLen) {
    iEnd = iLen;
  } else {
    iEnd = start + len;
  }
  return String(str).substring(start,iEnd);
}

function Len(str) {
  return String(str).length;  
}

function InStr(strSearch, charSearchFor) {
  for (i=0; i < Len(strSearch); i++) {
    if (charSearchFor == Mid(strSearch, i, 1)) {
      return i;
    }
  }
  return -1;
}

function setthefocus(formname,fieldname) {
// this function places focus on a specific field in a specific form
// parameters: formname, fieldname
  if(document.forms[formname]) {
    document.forms[formname].elements[fieldname].focus();
  }
}

function setthefocus_dom(id) {
// this function places focus on a specific field in a specific form
// parameters: id (the id of the form element to receive focus)
  if(document.getElementById(id)) {
		forminput=document.getElementById(id);
		forminput.focus();
  }
}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function Replace(stPhrase,stPattern,stInsert) 
{ 
	if(stPhrase.length>0) {
	   var stBuffer; 
		 var stArray=stPhrase.split(stPattern); 
	   stBuffer=""; 
	   for(var i=0; i<stArray.length; i++) 
	   { 
	        if(i<stArray.length-1) 
	       { 
	           stBuffer+=stArray[i]+stInsert; 
	       } 
	       else 
	       { 
	           stBuffer+=stArray[i]; 
	       } 
	   } 
	   return stBuffer; 
	} else {
		return stPhrase;
	}
}


function PCase(STRING) {
	var strReturn_Value = "";
	var iTemp = STRING.length;
	if(iTemp==0) {
		return"";
	}
	var UcaseNext = false;
	strReturn_Value += STRING.charAt(0).toUpperCase();
	for(var iCounter=1;iCounter < iTemp;iCounter++){
		if(UcaseNext == true) {
			strReturn_Value += STRING.charAt(iCounter).toUpperCase();
		} else {
			strReturn_Value += STRING.charAt(iCounter).toLowerCase();
		}
		var iChar = STRING.charCodeAt(iCounter);
		if(iChar == 32 || iChar == 45 || iChar == 46) {
			UcaseNext = true;
		} else {
			UcaseNext = false
		}
		if(iChar == 99 || iChar == 67) {
			if(STRING.charCodeAt(iCounter-1)==77 || STRING.charCodeAt(iCounter-1)==109) {
				UcaseNext = true;
			}
		}
	}
	return strReturn_Value;
}


function IsNumeric(sText) {
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
         IsNumber = false;
      }
   }
   return IsNumber;
}


function isDate(DateToCheck){
  if(DateToCheck==""){
    return true;
  }
  var m_strDate = FormatDate(DateToCheck);
  if(m_strDate==""){
    return false;
  }
  var m_arrDate = m_strDate.split("/");
  var m_DAY = m_arrDate[0];
  var m_MONTH = m_arrDate[1];
  var m_YEAR = m_arrDate[2];
  if(m_YEAR.length > 4){
    return false;
  }
  m_strDate = m_MONTH + "/" + m_DAY + "/" + m_YEAR;
  var testDate=new Date(m_strDate);
  if(testDate.getMonth()+1==m_MONTH){
    return true;
  } else {
    return false;
  }
} //end function






function FormatDate(DateToFormat,FormatAs){
  if(DateToFormat=="") {
    return"";
  }
  if(!FormatAs) {
    FormatAs="dd/mm/yyyy";
  }
  var strReturnDate;
  FormatAs = FormatAs.toLowerCase();
  DateToFormat = DateToFormat.toLowerCase();
  var arrDate
  var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var strMONTH;
  var Separator;
  while(DateToFormat.indexOf("st")>-1) {
    DateToFormat = DateToFormat.replace("st","");
  }
  while(DateToFormat.indexOf("nd")>-1) {
    DateToFormat = DateToFormat.replace("nd","");
  }
  while(DateToFormat.indexOf("rd")>-1) {
    DateToFormat = DateToFormat.replace("rd","");
  }
  while(DateToFormat.indexOf("th")>-1) {
    DateToFormat = DateToFormat.replace("th","");
  }
  if(DateToFormat.indexOf(".")>-1) {
    Separator = ".";
  }
  if(DateToFormat.indexOf("-")>-1) {
    Separator = "-";
  }
  if(DateToFormat.indexOf("/")>-1) {
    Separator = "/";
  }
  if(DateToFormat.indexOf(" ")>-1) {
    Separator = " ";
  }
  arrDate = DateToFormat.split(Separator);
  DateToFormat = "";
  for(var iSD = 0;iSD < arrDate.length;iSD++) {
    if(arrDate[iSD]!="")
    {
      DateToFormat += arrDate[iSD] + Separator;
    }
  }
  DateToFormat = DateToFormat.substring(0,DateToFormat.length-1);
  arrDate = DateToFormat.split(Separator);
  if(arrDate.length < 3) {
    return "";
  }
  var DAY = arrDate[0];
  var MONTH = arrDate[1];
  var YEAR = arrDate[2];
  if(parseFloat(arrDate[1]) > 12) {
    DAY = arrDate[1];
    MONTH = arrDate[0];
  }
  if(parseFloat(DAY) && DAY.toString().length==4) {
    YEAR = arrDate[0];
    DAY = arrDate[2];
    MONTH = arrDate[1];
  }
  for(var iSD = 0;iSD < arrMonths.length;iSD++) {
    var ShortMonth = arrMonths[iSD].substring(0,3).toLowerCase();
    var MonthPosition = DateToFormat.indexOf(ShortMonth);
    if(MonthPosition > -1) {
      MONTH = iSD + 1;
      if(MonthPosition == 0)  {
        DAY = arrDate[1];
        YEAR = arrDate[2];
      }
      break;
    }
  }
  var strTemp = YEAR.toString();
  if(strTemp.length==2) {
    if(parseFloat(YEAR)>40) {
      YEAR = "19" + YEAR;
    } else {
      YEAR = "20" + YEAR;
    }
  }
  if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)  {
    MONTH = "0" + MONTH;
  }
  if(parseInt(DAY)< 10 && DAY.toString().length < 2)  {
    DAY = "0" + DAY;
  }
  switch (FormatAs) {
    case "dd/mm/yyyy":
      return DAY + "/" + MONTH + "/" + YEAR;
    case "mm/dd/yyyy":
      return MONTH + "/" + DAY + "/" + YEAR;
    case "dd/mmm/yyyy":
      return DAY + " " + arrMonths[MONTH -1].substring(0,3) + " " + YEAR;
    case "mmm/dd/yyyy":
      return arrMonths[MONTH -1].substring(0,3) + " " + DAY + " " + YEAR;
    case "dd/mmmm/yyyy":
      return DAY + " " + arrMonths[MONTH -1] + " " + YEAR;	
    case "mmmm/dd/yyyy":
      return arrMonths[MONTH -1] + " " + DAY + " " + YEAR;
  }
  return DAY + "/" + strMONTH + "/" + YEAR;;
} // End Function

function clean_phone_no(thephoneno) {
	var chars='0123456789';
	var badchars='';
	for(i=0;i<thephoneno.length;i++) {
		thischar=thephoneno.charAt(i);
		chartest=chars.indexOf(thischar);
		if (chartest==-1) {
			badchars+=thischar;
		}
	}
	for (i=0;i<badchars.length;i++) {
		thephoneno=Replace(thephoneno,badchars.charAt(i),'');
	}
  return thephoneno;
}

/*	EventCache Version 1.0
	Copyright 2005 Mark Wubben

	Provides a way for automagically removing events from nodes and thus preventing memory leakage.
	See <http://novemberborn.net/javascript/event-cache> for more information.
	
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/

/*	Implement array.push for browsers which don't support it natively.
	Please remove this if it's already in other code */
if(Array.prototype.push == null){
	Array.prototype.push = function(){
		for(var i = 0; i < arguments.length; i++){
			this[this.length] = arguments[i];
		};
		return this.length;
	};
};

/*	Event Cache uses an anonymous function to create a hidden scope chain.
	This is to prevent scoping issues. */
var EventCache = function(){
	var listEvents = [];
	
	return {
		listEvents : listEvents,
	
		add : function(node, sEventName, fHandler, bCapture){
			listEvents.push(arguments);
		},
	
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				
				/* From this point on we need the event names to be prefixed with 'on" */
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				
				item[0][item[1]] = null;
			};
		}
	};
}();


function createProg(msg) {
  // Create Progressbar so people know to wait
	if (document.getElementById('domcontainer')) {
	
	  // create div
	  var prog=document.createElement('div');
	  
	  // assign div with 'progressbar' id to get CSS
	  prog.setAttribute('id','progressbar');
	
	  // create child node: X button at top right
	  var progclose=document.createElement('img');
	  progclose.setAttribute('src','/images/x.jpg');
	  progclose.setAttribute('id','x');
	  progclose.setAttribute('title','Close this progress bar');
	  progclose.setAttribute('alt','Close this progress bar');
	
	  // create child node: text message
	  var progtext=document.createTextNode(msg);
	
	  // create child node: progressbar image
	  var progbar=document.createElement('img');
	  progbar.setAttribute('src','/images/progress_ani.gif');
	
	  // append the three child nodes to prog
	  prog.appendChild(progclose);
	  prog.appendChild(progtext);
	  prog.appendChild(progbar);
	
	  // append prog to the existing empty domcontainer div
	  document.getElementById('domcontainer').appendChild(prog);
	
	  // add onclick event to X button
	  document.getElementById('x').onclick=function() {
	    destroyProg();
	  }
	}
}

function destroyProg() {
  if (document.getElementById('progressbar')) {
    node=document.getElementById('domcontainer');
    node.removeChild(node.childNodes[0]);
  }
}

function compareDates(firstdate, seconddate, range) {
	// checks to see if the difference between two dates is larger than the specified range
	therange=1000*60*60*24*range;
	firstdate_calc=firstdate.getTime();
	seconddate_calc=seconddate.getTime();
	if (firstdate_calc+therange<seconddate_calc) {
		return false;
	}
	return true;
}


addEvent(window, "unload", EventCache.flush);