// JavaScript Document

//FormManager
var FORM_MANAGER_CONDITION_SEPARATOR = " AND ";
var FORM_MANAGER_POSSIBILITY_SEPARATOR = " OR ";
var FORM_MANAGER_NAME_VALUE_SEPARATOR = " BEING ";
var FORM_MANAGER_DEPENDS = "DEPENDS ON ";
var FORM_MANAGER_CONFLICTS = "CONFLICTS WITH ";
var FORM_MANAGER_EMPTY = "EMPTY";

function addEvent(el, ev, f) {
  if(el.addEventListener)
    el.addEventListener(ev, f, false);
  else if(el.attachEvent) {
    var t = function() {
      f.apply(el);
    };
    addEvent.events.push({'element': el, 'event': ev, 'handler': f});
    el.attachEvent("on" + ev, t);
  } else
    el['on' + ev] = f;
}

function addEvents(els, evs, f) {
  for(var i = 0; i < els.length; ++i)
    for(var j = 0; j < evs.length; ++j)
      addEvent(els[i], evs[j], f);
}

addEvent.events = [];

if(typeof window.event !== "undefined")
  addEvent(window, "unload", function() {
      for(var i = 0, e = addEvent.events; i < e.length; ++i)
        e[i].element.detachEvent("on" + e[i].event, e[i].handler);
    }
  );

function getRadioValue(el) {
  if(!el.length) return null;
  for(var i = 0; i < el.length; ++i)
    if(el[i].checked) return el[i].value;
  return null;
}

function getSelectValue(el) {
  if(!el.tagName  || el.tagName.toLowerCase() !== "select")
    return null;
  return el.options[el.selectedIndex].value;
}

function isElementValue(el, v) {
  if(v === FORM_MANAGER_EMPTY) v = '';
  return (
    getRadioValue(el) == v ||
    getSelectValue(el) == v ||
    (
      el.tagName &&
      el.tagName.toLowerCase() !== "select" &&
      el.value == v
    )
  );
}

function setupDependencies() {
  var showEl = function() {
    this.style.display = "";
    if(this.parentNode.tagName.toLowerCase() == "label")
      this.parentNode.style.display = "";
  };
  var hideEl = function() {
    this.style.display = "none";
    if(typeof this.checked !== "undefined") this.checked = false;
    else this.value = "";
    if(this.parentNode.tagName.toLowerCase() == "label")
      this.parentNode.style.display = "none";
    this.hidden = true;
  };
  var calcDeps = function() {
    for(var i = 0, e = this.elements; i < e.length; ++i) {
      e[i].hidden = false;
      for(var j = 0, f = e[i].className.split(FORM_MANAGER_CONDITION_SEPARATOR); j < f.length; ++j)
        if(f[j].indexOf(FORM_MANAGER_DEPENDS) === 0) {
          for(var k = 0, g = f[j].substr(FORM_MANAGER_DEPENDS.length).split(FORM_MANAGER_POSSIBILITY_SEPARATOR); k < g.length; ++k)
            if(g[k].indexOf(FORM_MANAGER_NAME_VALUE_SEPARATOR) === -1) {
	      if(e[g[k]] && e[g[k]].checked) break;
            else if(k + 1 == g.length)
                e[i].hide();
            } else {
              var n = g[k].split(FORM_MANAGER_NAME_VALUE_SEPARATOR),
                v = n[1];
              n = n[0];
	      if(e[n])
	        if(isElementValue(e[n], v)) break;
	        else if(k + 1 == g.length) e[i].hide();
	    }
        } else if(f[j].indexOf(FORM_MANAGER_CONFLICTS) === 0) {
          if(f[j].indexOf(FORM_MANAGER_NAME_VALUE_SEPARATOR) === -1) {
	    if(e[f[j].substr(FORM_MANAGER_CONFLICTS.length)] && e[f[j].substr(FORM_MANAGER_CONFLICTS.length)].checked) {
              e[i].hide();
              break;
            }
          } else {
            var n = f[j].substr(FORM_MANAGER_CONFLICTS.length).split(FORM_MANAGER_NAME_VALUE_SEPARATOR),
              v = n[1];
            n = n[0];
            if(e[n]) {
              if(isElementValue(e[n], v)) {
                e[i].hide();
                break;
              }
            }
          }
        }
      if(!e[i].hidden) e[i].show();
    }
  };
  var changeHandler = function() {
    this.form.calculateDependencies();
    return true;
  };
  for(var i = 0; i < arguments.length; ++i) {
    for(var j = 0, e = window.document.forms[arguments[i]].elements; j < e.length; ++j) {
      addEvents([e[j]], ["change", "keyup", "focus", "click", "keydown"], changeHandler);
      e[j].hide = hideEl;
      e[j].show = showEl;
    }

    (e = window.document.forms[arguments[i]]).calculateDependencies = calcDeps;
    e.calculateDependencies();
  }
}

//ALDER
var one_day=1000*60*60*24
var one_month=1000*60*60*24*30
var one_year=1000*60*60*24*30*12
function displayage(yr, mon, day, unit, decimal, round){ today=new Date()
var pastdate=new Date(yr, mon-1, day)
var countunit=unit
var decimals=decimal
var rounding=round
finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year
decimals=(decimals<=0)? 1 : decimals*10
if (unit!="&aring;r siden)"){ if (rounding=="rounddown")
document.write(Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit)
else
document.write(Math.ceil((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals+" "+countunit)
}
else{ yearspast=today.getFullYear()-yr-1
tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
pastdate.setFullYear(today.getFullYear())
pastdate2=new Date(today.getFullYear()-1, mon-1, day)
tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
document.write(yearspast+tail+" "+countunit)
}
}



//DROPDOWNTABS
//Drop Down Tabs Menu- Author: Dynamic Drive (http://www.dynamicdrive.com)

//Created: May 16th, 07'
var tabdropdown={
	disappeardelay: 200, //set delay in miliseconds before menu disappears onmouseout
	disablemenuclick: false, //when user clicks on a menu item with a drop down menu, disable menu item's link?
	enableiframeshim: 1, //1 or 0, for true or false

	//No need to edit beyond here////////////////////////
	dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, previousmenuitem:null,
	currentpageurl: window.location.href.replace("http://"+window.location.hostname, "").replace(/^\//, ""), //get current page url (minus hostname, ie: http://www.dynamicdrive.com/)

	getposOffset:function(what, offsettype){
		var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
		var parentEl=what.offsetParent;
			while (parentEl!=null){
				totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
				parentEl=parentEl.offsetParent;
			}
		return totaloffset;
	},

	showhide:function(obj, e, obj2){ //obj refers to drop down menu, obj2 refers to tab menu item mouse is currently over
		if (this.ie || this.firefox)
			this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
		if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
			if (obj2.parentNode.className.indexOf("default")==-1) //if tab isn't a default selected one
				obj2.parentNode.className="selected"
			obj.visibility="visible"
			}
		else if (e.type=="click")
			obj.visibility="hidden"
	},

	iecompattest:function(){
		return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
	},

	clearbrowseredge:function(obj, whichedge){
		var edgeoffset=0
		if (whichedge=="rightedge"){
			var windowedge=this.ie && !window.opera? this.standardbody.scrollLeft+this.standardbody.clientWidth-15 : window.pageXOffset+window.innerWidth-15
			this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
		if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
			edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
		}
		else{
			var topedge=this.ie && !window.opera? this.standardbody.scrollTop : window.pageYOffset
			var windowedge=this.ie && !window.opera? this.standardbody.scrollTop+this.standardbody.clientHeight-15 : window.pageYOffset+window.innerHeight-18
			this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
			if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
				edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
				if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
					edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
			}
			this.dropmenuobj.firstlink.style.borderTopWidth=(edgeoffset==0)? 0 : "1px" //Add 1px top border to menu if dropping up
		}
		return edgeoffset
	},

	dropit:function(obj, e, dropmenuID){
		if (this.dropmenuobj!=null){ //hide previous menu
			this.dropmenuobj.style.visibility="hidden" //hide menu
			if (this.previousmenuitem!=null && this.previousmenuitem!=obj){
				if (this.previousmenuitem.parentNode.className.indexOf("default")==-1) //If the tab isn't a default selected one
					this.previousmenuitem.parentNode.className=""
			}
		}
		this.clearhidemenu()
		if (this.ie||this.firefox){
			obj.onmouseout=function(){tabdropdown.delayhidemenu(obj)}
			obj.onclick=function(){return !tabdropdown.disablemenuclick} //disable main menu item link onclick?
			this.dropmenuobj=document.getElementById(dropmenuID)
			this.dropmenuobj.onmouseover=function(){tabdropdown.clearhidemenu()}
			this.dropmenuobj.onmouseout=function(e){tabdropdown.dynamichide(e, obj)}
			this.dropmenuobj.onclick=function(){tabdropdown.delayhidemenu(obj)}
			this.showhide(this.dropmenuobj.style, e, obj)
			this.dropmenuobj.x=this.getposOffset(obj, "left")
			this.dropmenuobj.y=this.getposOffset(obj, "top")
			this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
			this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
			this.previousmenuitem=obj //remember main menu item mouse moved out from (and into current menu item)
			this.positionshim() //call iframe shim function
		}
	},

	contains_firefox:function(a, b) {
		while (b.parentNode)
		if ((b = b.parentNode) == a)
			return true;
		return false;
	},

	dynamichide:function(e, obj2){ //obj2 refers to tab menu item mouse is currently over
		var evtobj=window.event? window.event : e
		if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
			this.delayhidemenu(obj2)
		else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
			this.delayhidemenu(obj2)
	},

	delayhidemenu:function(obj2){
		this.delayhide=setTimeout(function(){tabdropdown.dropmenuobj.style.visibility='hidden'; if (obj2.parentNode.className.indexOf('default')==-1) obj2.parentNode.className=''},this.disappeardelay) //hide menu
	},

	clearhidemenu:function(){
		if (this.delayhide!="undefined")
			clearTimeout(this.delayhide)
	},

	positionshim:function(){ //display iframe shim function
		if (this.enableiframeshim && typeof this.shimobject!="undefined"){
			if (this.dropmenuobj.style.visibility=="visible"){
				this.shimobject.style.width=this.dropmenuobj.offsetWidth+"px"
				this.shimobject.style.height=this.dropmenuobj.offsetHeight+"px"
				this.shimobject.style.left=this.dropmenuobj.style.left
				this.shimobject.style.top=this.dropmenuobj.style.top
			}
		this.shimobject.style.display=(this.dropmenuobj.style.visibility=="visible")? "block" : "none"
		}
	},

	hideshim:function(){
		if (this.enableiframeshim && typeof this.shimobject!="undefined")
			this.shimobject.style.display='none'
	},

isSelected:function(menuurl){
	var menuurl=menuurl.replace("http://"+menuurl.hostname, "").replace(/^\//, "")
	return (tabdropdown.currentpageurl==menuurl)
},

	init:function(menuid, dselected){
		this.standardbody=(document.compatMode=="CSS1Compat")? document.documentElement : document.body //create reference to common "body" across doctypes
		var menuitems=document.getElementById(menuid).getElementsByTagName("a")
		for (var i=0; i<menuitems.length; i++){
			if (menuitems[i].getAttribute("rel")){
				var relvalue=menuitems[i].getAttribute("rel")
				document.getElementById(relvalue).firstlink=document.getElementById(relvalue).getElementsByTagName("a")[0]
				menuitems[i].onmouseover=function(e){
					var event=typeof e!="undefined"? e : window.event
					tabdropdown.dropit(this, event, this.getAttribute("rel"))
				}
			}
			if (dselected=="auto" && typeof setalready=="undefined" && this.isSelected(menuitems[i].href)){
				menuitems[i].parentNode.className+=" selected default"
				var setalready=true
			}
			else if (parseInt(dselected)==i)
				menuitems[i].parentNode.className+=" selected default"
		}
	}
}


//** Animated Collapsible DIV v2.0- (c) Dynamic Drive DHTML code library: http://www.dynamicdrive.com.
//** May 24th, 08'- Script rewritten and updated to 2.0.
//** June 4th, 08'- Version 2.01: Bug fix to work with jquery 1.2.6 (which changed the way attr() behaves).
//** March 5th, 09'- Version 2.2, which adds the following:
			//1) ontoggle($, divobj, state) event that fires each time a DIV is expanded/collapsed, including when the page 1st loads
			//2) Ability to expand a DIV via a URL parameter string, ie: index.htm?expanddiv=jason or index.htm?expanddiv=jason,kelly

//** March 9th, 09'- Version 2.2.1: Optimized ontoggle event handler slightly.
//** July 3rd, 09'- Version 2.4, which adds the following:
			//1) You can now insert rel="expand[divid] | collapse[divid] | toggle[divid]" inside arbitrary links to act as DIV togglers
			//2) For image toggler links, you can insert the attributes "data-openimage" and "data-closedimage" to update its image based on the DIV state

var animatedcollapse={
divholders: {}, //structure: {div.id, div.attrs, div.$divref, div.$togglerimage}
divgroups: {}, //structure: {groupname.count, groupname.lastactivedivid}
lastactiveingroup: {}, //structure: {lastactivediv.id}
preloadimages: [],

show:function(divids){ //public method
	if (typeof divids=="object"){
		for (var i=0; i<divids.length; i++)
			this.showhide(divids[i], "show")
	}
	else
		this.showhide(divids, "show")
},

hide:function(divids){ //public method
	if (typeof divids=="object"){
		for (var i=0; i<divids.length; i++)
			this.showhide(divids[i], "hide")
	}
	else
		this.showhide(divids, "hide")
},

toggle:function(divid){ //public method
	if (typeof divid=="object")
		divid=divid[0]
	this.showhide(divid, "toggle")
},

addDiv:function(divid, attrstring){ //public function
	this.divholders[divid]=({id: divid, $divref: null, attrs: attrstring})
	this.divholders[divid].getAttr=function(name){ //assign getAttr() function to each divholder object
		var attr=new RegExp(name+"=([^,]+)", "i") //get name/value config pair (ie: width=400px,)
		return (attr.test(this.attrs) && parseInt(RegExp.$1)!=0)? RegExp.$1 : null //return value portion (string), or 0 (false) if none found
	}
	this.currentid=divid //keep track of current div object being manipulated (in the event of chaining)
	return this
},

showhide:function(divid, action){
	var $divref=this.divholders[divid].$divref //reference collapsible DIV
	if (this.divholders[divid] && $divref.length==1){ //if DIV exists
		var targetgroup=this.divgroups[$divref.attr('groupname')] //find out which group DIV belongs to (if any)
		if ($divref.attr('groupname') && targetgroup.count>1 && (action=="show" || action=="toggle" && $divref.css('display')=='none')){ //If current DIV belongs to a group
			if (targetgroup.lastactivedivid && targetgroup.lastactivedivid!=divid) //if last active DIV is set
				this.slideengine(targetgroup.lastactivedivid, 'hide') //hide last active DIV within group first
				this.slideengine(divid, 'show')
			targetgroup.lastactivedivid=divid //remember last active DIV
		}
		else{
			this.slideengine(divid, action)
		}
	}
},

slideengine:function(divid, action){
	var $divref=this.divholders[divid].$divref
	var $togglerimage=this.divholders[divid].$togglerimage
	if (this.divholders[divid] && $divref.length==1){ //if this DIV exists
		var animateSetting={height: action}
		if ($divref.attr('fade'))
			animateSetting.opacity=action
		$divref.animate(animateSetting, $divref.attr('speed')? parseInt($divref.attr('speed')) : 500, function(){
			if ($togglerimage){
				$togglerimage.attr('src', ($divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open)
			}
			if (animatedcollapse.ontoggle){
				try{
					animatedcollapse.ontoggle(jQuery, $divref.get(0), $divref.css('display'))
				}
				catch(e){
					alert("An error exists inside your \"ontoggle\" function:\n\n"+e+"\n\nAborting execution of function.")
				}
			}
		})
		return false
	}
},

generatemap:function(){
	var map={}
	for (var i=0; i<arguments.length; i++){
		if (arguments[i][1]!=null){ //do not generate name/value pair if value is null
			map[arguments[i][0]]=arguments[i][1]
		}
	}
	return map
},

init:function(){
	var ac=this
	jQuery(document).ready(function($){
		animatedcollapse.ontoggle=animatedcollapse.ontoggle || null
		var urlparamopenids=animatedcollapse.urlparamselect() //Get div ids that should be expanded based on the url (['div1','div2',etc])
		var persistopenids=ac.getCookie('acopendivids') //Get list of div ids that should be expanded due to persistence ('div1,div2,etc')
		var groupswithpersist=ac.getCookie('acgroupswithpersist') //Get list of group names that have 1 or more divs with "persist" attribute defined
		if (persistopenids!=null) //if cookie isn't null (is null if first time page loads, and cookie hasnt been set yet)
			persistopenids=(persistopenids=='nada')? [] : persistopenids.split(',') //if no divs are persisted, set to empty array, else, array of div ids
		groupswithpersist=(groupswithpersist==null || groupswithpersist=='nada')? [] : groupswithpersist.split(',') //Get list of groups with divs that are persisted
		jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object
			this.$divref=$('#'+this.id)
			if ((this.getAttr('persist') || jQuery.inArray(this.getAttr('group'), groupswithpersist)!=-1) && persistopenids!=null){ //if this div carries a user "persist" setting, or belong to a group with at least one div that does
				var cssdisplay=(jQuery.inArray(this.id, persistopenids)!=-1)? 'block' : 'none'
			}
			else{
				var cssdisplay=this.getAttr('hide')? 'none' : null
			}
			if (urlparamopenids[0]=="all" || jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains the single array element "all", or this div's ID
				cssdisplay='block' //set div to "block", overriding any other setting
			}
			else if (urlparamopenids[0]=="none"){
				cssdisplay='none' //set div to "none", overriding any other setting
			}
			this.$divref.css(ac.generatemap(['height', this.getAttr('height')], ['display', cssdisplay]))
			this.$divref.attr(ac.generatemap(['groupname', this.getAttr('group')], ['fade', this.getAttr('fade')], ['speed', this.getAttr('speed')]))
			if (this.getAttr('group')){ //if this DIV has the "group" attr defined
				var targetgroup=ac.divgroups[this.getAttr('group')] || (ac.divgroups[this.getAttr('group')]={}) //Get settings for this group, or if it no settings exist yet, create blank object to store them in
				targetgroup.count=(targetgroup.count||0)+1 //count # of DIVs within this group
				if (jQuery.inArray(this.id, urlparamopenids)!=-1){ //if url parameter string contains this div's ID
					targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded). Overrides other settings
					targetgroup.overridepersist=1 //Indicate to override persisted div that would have been expanded
				}
				if (!targetgroup.lastactivedivid && this.$divref.css('display')!='none' || cssdisplay=="block" && typeof targetgroup.overridepersist=="undefined") //if this DIV was open by default or should be open due to persistence								
					targetgroup.lastactivedivid=this.id //remember this DIV as the last "active" DIV (this DIV will be expanded)
				this.$divref.css({display:'none'}) //hide any DIV that's part of said group for now
			}
		}) //end divholders.each
		jQuery.each(ac.divgroups, function(){ //loop through each group
			if (this.lastactivedivid && urlparamopenids[0]!="none") //show last "active" DIV within each group (one that should be expanded), unless url param="none"
				ac.divholders[this.lastactivedivid].$divref.show()
		})
		if (animatedcollapse.ontoggle){
			jQuery.each(ac.divholders, function(){ //loop through each collapsible DIV object and fire ontoggle event
				animatedcollapse.ontoggle(jQuery, this.$divref.get(0), this.$divref.css('display'))
			})
		}
 		//Parse page for links containing rel attribute
		var $allcontrols=$('a[rel]').filter('[rel^="collapse["], [rel^="expand["], [rel^="toggle["]') //get all elements on page with rel="collapse[]", "expand[]" and "toggle[]"
		$allcontrols.each(function(){ //loop though each control link
			this._divids=this.getAttribute('rel').replace(/(^\w+)|(\s+)/g, "").replace(/[\[\]']/g, "") //cache value 'div1,div2,etc' within identifier[div1,div2,etc]
			if (this.getElementsByTagName('img').length==1 && ac.divholders[this._divids]){ //if control is an image link that toggles a single DIV (must be one to one to update status image)
				animatedcollapse.preloadimage(this.getAttribute('data-openimage'), this.getAttribute('data-closedimage')) //preload control images (if defined)
				$togglerimage=$(this).find('img').eq(0).data('srcs', {open:this.getAttribute('data-openimage'), closed:this.getAttribute('data-closedimage')}) //remember open and closed images' paths
				ac.divholders[this._divids].$togglerimage=$(this).find('img').eq(0) //save reference to toggler image (to be updated inside slideengine()
				ac.divholders[this._divids].$togglerimage.attr('src', (ac.divholders[this._divids].$divref.css('display')=="none")? $togglerimage.data('srcs').closed : $togglerimage.data('srcs').open)
			}
			$(this).click(function(){ //assign click behavior to each control link
				var relattr=this.getAttribute('rel')
				var divids=(this._divids=="")? [] : this._divids.split(',') //convert 'div1,div2,etc' to array 
				if (divids.length>0){
					animatedcollapse[/expand/i.test(relattr)? 'show' : /collapse/i.test(relattr)? 'hide' : 'toggle'](divids) //call corresponding public function
					return false
				}
			}) //end control.click
		})// end control.each

		$(window).bind('unload', function(){
			ac.uninit()
		})
	}) //end doc.ready()
},

uninit:function(){
	var opendivids='', groupswithpersist=''
	jQuery.each(this.divholders, function(){
		if (this.$divref.css('display')!='none'){
			opendivids+=this.id+',' //store ids of DIVs that are expanded when page unloads: 'div1,div2,etc'
		}
		if (this.getAttr('group') && this.getAttr('persist'))
			groupswithpersist+=this.getAttr('group')+',' //store groups with which at least one DIV has persistance enabled: 'group1,group2,etc'
	})
	opendivids=(opendivids=='')? 'nada' : opendivids.replace(/,$/, '')
	groupswithpersist=(groupswithpersist=='')? 'nada' : groupswithpersist.replace(/,$/, '')
	this.setCookie('acopendivids', opendivids)
	this.setCookie('acgroupswithpersist', groupswithpersist)
},

getCookie:function(Name){ 
	var re=new RegExp(Name+"=[^;]*", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return null
},

setCookie:function(name, value, days){
	if (typeof days!="undefined"){ //if set persistent cookie
		var expireDate = new Date()
		expireDate.setDate(expireDate.getDate()+days)
		document.cookie = name+"="+value+"; path=/; expires="+expireDate.toGMTString()
	}
	else //else if this is a session only cookie
		document.cookie = name+"="+value+"; path=/"
},

urlparamselect:function(){
	window.location.search.match(/expanddiv=([\w\-_,]+)/i) //search for expanddiv=divid or divid1,divid2,etc
	return (RegExp.$1!="")? RegExp.$1.split(",") : []
},

preloadimage:function(){
	var preloadimages=this.preloadimages
	for (var i=0; i<arguments.length; i++){
		if (arguments[i] && arguments[i].length>0){
			preloadimages[preloadimages.length]=new Image()
			preloadimages[preloadimages.length-1].src=arguments[i]
		}
	}
}

}


// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
// Update Oct 2005: minor tidy-up: unused parameter removed
// Update Jun 2006: minor improvements to variable names and layout
// ----------------------------------------------------------------------
var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread
// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}
// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------
function setFocusDelayed()
{
  global_valfield.focus();
}
function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}
// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;
  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;   
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}
// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------
var proceed = 2;  
function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem.firstChild) return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  
  if (emptyString.test(valfield.value)) {
    if (required) {
      msg (infofield, "error", "*");  
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
      return true;  
    }
  }
  return proceed;
}
// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------
function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;
  msg (infofield, "warn", "");  
  return true;
}
// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------
function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;
  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "error", "*");
    return false;
  }
  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "warn", "?");
  else
    msg (infofield, "warn", "");
  return true;
}
