// Multi-select list function
function _toggle(id, separator, force_hidden) {
  var el = $(id)
  var ieframe = $('ie' + id)
  if ((force_hidden === true) || (el.style.visibility == 'visible')) {
    el.style.visibility = 'hidden'
    ieframe.style.display = 'none'
  }
  else {
    var input = $(id + '_values')
		var coords = Position.cumulativeOffset(input)
		var fleft = coords[0] - 28
		var ftop = coords[1] - 24
    el.style.top=(ftop) + 'px'
    el.style.left=fleft + 'px'
    el.style.visibility = 'visible'

    // See dotnetjunkies.com/WebLog/jking/archive/2003/10/30/2975.aspx
    ieframe.style.width = el.offsetWidth
    ieframe.style.height = el.offsetHeight
    ieframe.style.top = el.style.top
    ieframe.style.left = el.style.left
    ieframe.style.zIndex = el.style.zIndex - 1
    ieframe.style.display = 'block'
  }

  updateList(id, separator)
  return(false)
}

function checkem(name, bool) {
  var count = 0
  var id = name + count
  var el = $(id)
  while (el != null) {
    el.checked = bool
    count++
    id = name + count
    el = $(id)
  }
  return(false)
}

function updateList(name, separator) {
  var count = 0
  var values = ''
  var string = ''
  var id = name + '0'
  var el = $(id)
  while (el != null) {
    if (el.checked) {
      string += (string != '' ? separator : '') + el.getAttribute('xstring')
    }

    count++
    id = name + count
    el = $(id)
  }

  var input_id = name + '_values'
  el = $(input_id)
  el.value = string
  el.title = string
}

var ua = navigator.userAgent.toLowerCase()
var isSafari = (ua.indexOf('safari') != - 1)
var isMacIE = (ua.indexOf('msie') != - 1) && (ua.indexOf('mac_') != - 1)
var isIE6 = (ua.indexOf('msie 6') != - 1)

// Get the top coord of the element
function getRealTop(el) {
  var yPos = el.offsetTop - (el.scrollTop ? el.scrollTop : 0) + (isSafari || isMacIE ? 0 : getScrollTop())
  tempEl = el.offsetParent
  while (tempEl != null) {
    yPos += tempEl.offsetTop - (tempEl.parentNode.scrollTop == null ? 0 : tempEl.parentNode.scrollTop)
    tempEl = tempEl.offsetParent
  }
  return(yPos)
}

// Get the left coord of the element
function getRealLeft(el) {
  var xPos = el.offsetLeft
  tempEl = el.offsetParent
  while (tempEl != null) {
    xPos += tempEl.offsetLeft
    tempEl = tempEl.offsetParent
  }
  return(xPos)
}

// See www.quirksmode.org/viewport/compatibility.html
function getScrollTop() {
  var y
  if (self.pageYOffset) // all except Explorer
    {
      y = self.pageYOffset;
    }
  else if (document.documentElement && document.documentElement.scrollTop)
    // Explorer 6 Strict
    {
      y = document.documentElement.scrollTop;
    }
  else if (document.body) // all other Explorers
    {
      y = document.body.scrollTop;
    }

  return(y)
}

/* Cookie functions from www.netspade.com/articles/2005/11/16/javascript-cookies/ */
/*
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/*
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/*
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// Check if a number is between two others
// Display a message if not and return false
function cknum(id, min, max, name) {
	var field = document.getElementById(id)
	var val = field.value
	if (val == '') {
		val = 0
	}
	if (!isInt(val)) {
		alert(name + ' must be a whole number between ' + min + ' and ' + max)
		field.focus()
		return(true)
	}
	if (val < min) {
		alert(name + ' must be at least ' + min)
		field.focus()
		return(true)
	}
	if (val > max) {
		alert(name + ' must be less than or equal to ' + max)
		field.focus()
		return(true)
	}
	return(false)
}

// Return true if parm is an integer
function isInt(str) {
	var i = parseInt(str)
	if (isNaN(i)) {
		return(false)
	}
	i = i.toString ()
	if (i != str)
		return(false)
	return(true)
}

// Check if a number is between two others
// Display a message if not and return false
function ckdec(id, min, max, name) {
	var field = document.getElementById(id)
	var val = field.value
	if (val == '') {
		field.value = 0
		return(false)
	}
	if (!isFloat(val)) {
		alert(name + ' must be a number between ' + min + ' and ' + max)
		field.focus()
		return(true)
	}
	if (val < min) {
		alert(name + ' must be at least ' + min)
		field.focus()
		return(true)
	}
	if (val > max) {
		alert(name + ' must be less than or equal to ' + max)
		field.focus()
		return(true)
	}
	return(false)
}

// Return true if parm is a float
function isFloat(str) {
	return(str == String(str).match(/[+-]{0,1}\d*\.{0,1}\d*/)[0]);
}

// Validate a 'date field'
// DD, MMxDD, MMxDDxYY, MMxDDxYYYY, YYYYxMMxDD, TOD(AY), 
// TOM(ORROW), Y(ESTERDAY)
//    where x is any non-numeric, printable character
// if 'required' is true, a date is required
//    otherwise an empty field is OK
// if 'asSqlDate' is true, date will be formatted as YYYY-MM-DD
//    otherwise it will be formatted as MM/DD/YYYY
function checkDate(field, required, asSqlDate) {

   asSqlDate = false

   err = ''
   val = field.value.toUpperCase()
   today = new Date()

   if ((val == '') && (required != true))
      return true

   if ((val.length >= 3) && (val.substring(0, 3) == 'TOD')) {
      day = today.getDate()
      month = today.getMonth() + 1
      year = today.getYear()
   } else if ((val.length >= 3) && (val.substring(0, 3) == 'TOM')) {
      date = new Date(today.getTime() + 86400000)
      day = date.getDate()
      month = date.getMonth() + 1
      year = date.getYear() 
   } else if (val.substring(0, 1) == 'Y') {
      date = new Date(today.getTime() - 86400000)
      day = date.getDate()
      month = date.getMonth() + 1
      year = date.getYear() 
   } else {

         // Month (or day or year)

      pos = 0  
      a = ''
      ch = val.substring(pos, pos+1)
      while ((ch >= '0') & (ch <= '9')) {
         a = a + ch
         pos += 1 
         ch = val.substring(pos, pos+1)
      }
      pos += 1

         // Day (or month)

      b = ''
      ch = val.substring(pos, pos+1)
      while ((ch >= '0') & (ch <= '9')) {
         b = b + ch
         pos += 1 
         ch = val.substring(pos, pos+1)
      }
      pos += 1

         // Year (or month)
   
      c = ''
      ch = val.substring(pos, pos+1)
      while ((ch >= '0') & (ch <= '9')) {
         c = c + ch
         pos += 1 
         ch = val.substring(pos, pos+1)
      }

         // Which format -> DD, MM/DD(/YYYY) or YYYY-MM-DD)

      if ((b == '') && (c == '')) {
         day = (a == '') ? 0 : parseInt(a, 10)
         month = today.getMonth() + 1
         year = today.getYear()
         if (year < 1900)
            year += 1900
      }
      else {
         a = (a == '') ? 0 : parseInt(a, 10)
         if (a > 12) {
            year = a
            month = (b == '') ? 0 : parseInt(b, 10)
            day = (c == '') ? 0 : parseInt(c, 10)
         }
         else {
            month = a
            day = (b == '') ? 0 : parseInt(b, 10)
            year = (c == '') ? -1 : parseInt(c, 10)
         }
      }
   }

      // Fill in this year if left out

   if (year == -1) {
      year = today.getYear()
      if (year < 1900)
         year += 1900
   }
   if (year < 100) {
      if (year < 50)
         year = 2000 + year
      else
        year = 1900 + year
   }

      // Check 'em

   if (month < 1 || month > 12)
      err = 'Bad month'
   if (day < 1 || day > 31)
      err = 'Bad day'
   if (year < 0)
      err = 'Bad year'
   if (month == 4 || month == 6 || month == 9 || month == 11) {
      if (day == 31)
         err = 'Bad day'
   }
   if (month == 2) {
      var g = parseInt(year / 4)
      if (isNaN(g)) {
         err = 'Bad year'
      }
      if (day > 29)
         err = 'Bad day'
      if (day == 29 && ((year / 4) != parseInt(year / 4)))
         err = 'Bad day'
   }
   if (year < 999)
      err = 'Bad year'
   if (year > 9999)
      err = 'Bad year'

      // Is it OK?
   if (err != '') {
      if (val == '')
         alert('Date Required')
      else
         if (confirm('Invalid Date.\n\nClick OK for help\nor Cancel to fix the date.'))
            alert('Dates may be entered in any of the following formats:\n\nDD, MM/DD, MM/DD/YY, MM/DD/YYYY, YYYY/MM/DD, TODAY, TOMORROW, YESTERDAY')

      field.focus()
      return false
   }
   else {
      if (asSqlDate)
         field.value = year + '-' + (month < 10 ? '0' + month : month) + '-' + 
                                    (day < 10 ? '0' + day : day)
      else
         field.value = month + '/' + day + '/' + year
      return true
   }
}

// Validate a 'time field'
// H H:M H:Ma H:Mp Noon Midnight NOW
// if 'required' is true, a time is required
//    otherwise an empty field is OK
function checkTime(field, required) {

   err = ''
   val = field.value.toLowerCase()

   if ((val == '') && (required != true))
      return true

   // Now
   if (val.substr(0, 3) == 'now') {
      d = new Date()
      min = d.getMinutes()
      if (min < 10) {
         min = '0' + min
      }
      hour = d.getHours()
      val = hour + ':' + min

      if (hour > 11)
         val = val + " pm"
      else
         val = val + " am"
   }

   // Midnight
   if (val.substring(0, 1) == 'm') {
      hour = '12'
      minute = '00'
      aorp = 'a'
   }
   // Noon
   else if (val.substring(0, 1) == 'n') {
      hour = '12'
      minute = '00'
      aorp = 'p'
   } else {

         // Hour

      pos = 0  
      hour = ''
      ch = val.substring(pos, pos+1)
      while ((ch >= '0') & (ch <= '9')) {
         hour = hour + ch
         pos += 1 
         ch = val.substring(pos, pos+1)
      }
      if ((ch != 'a') && (ch != 'p'))
         pos += 1

         // Minute

      minute = ''
      ch = val.substring(pos, pos+1)
      while ((ch >= '0') & (ch <= '9')) {
         minute = minute + ch
         pos += 1 
         ch = val.substring(pos, pos+1)
      }
      if (minute == '')
         minute = '00'
      if (minute.length == 1)
         minute = minute + '0'

         // am or pm
   
      aorp = ''
      ch = val.substring(pos, pos+1)
      while ((pos <= val.length) && (aorp == '')) {
         pos += 1
         if ((ch == 'a') || (ch == 'p'))
            aorp = ch
         ch = val.substring(pos, pos+1)
      }
      if (aorp == '') {
         if ((hour >= 7) && (hour <= 11))
            aorp = 'a'
         else
            aorp = 'p'
      }
   }

      // Check 'em

   if (hour == 24) {
      hour = 12
      aorp = 'a'
   }
   if (hour > 12) {
      hour = hour - 12
      aorp = 'p'
   }

   if (hour < 1 || hour > 24)
      err = 'Bad hour'
   if (minute < 0 || minute > 59)
      err = 'Bad minute'

      // Is it OK?

   if (err != '') {
      if (val == '')
         alert('Time Required')
      else {
         if (confirm('Invalid Time.\n\nClick OK for help\nor Cancel to fix the date.'))
            alert('Times may be entered in any of the following formats:\n\nHH, HH:MM, HH:MMa, HH:MMp, Noon, Midnight, NOW')
      }
      field.focus()
      return false
   }
   else {
      field.value = hour + ':' + minute + ' ' + aorp + 'm'
      return true
   }
}

// Limit the size of a textarea
function tasize(field, max) {
   if (field.value.length > max) {
      field.value = field.value.substr(0, max)
      return false }
   else
      return true
}

// Keep the session alive
// This checks to make sure the setTimeout() calls don't cascade (why do they?!?)
var next_keep_alive = 0
function keepalive() {
	var now = Date.parse(Date())
	if (now > next_keep_alive) {
		var offset = 1 * 60 * 1000
		setTimeout('keepalive()', offset)
		next_keep_alive = now + (offset * 0.95)
		document.getElementById('keepalive').src = '/jslib/keepalive.php?' + next_keep_alive
	}
}

// Set the selected value
// Select the first one if the value was not found
function set_select_value(select, value) {
	var options = select.options
	var set = false
	for (var i=options.length-1; i>=0; i--) {
		if (options[i].value == value) {
			options[i].selected = true
			set = true
		}
	}

	if (!set) {
		options[0].selected = true
	}
}

// Garrett Murphey
// http://gmurphey.com/
// Distributed under the Creative Commons Attribution-Sharealike License
// http://creativecommons.org/licenses/by-sa/2.5/
function align(e, position) {
	e = $(e);
	var container = Try.these(
		function () { return e.parentNode },
		function () { return e.parentElement },
		function () { return false });
	if (container != false) {
		var dimensions = Element.getDimensions(e);
		// Removed this line... interferes with 'display: none' to get Scriptaculous effects to work
		// e.removeAttribute('style');
		Element.setStyle(container, { position: 'relative' });
		for (var name in position) {
			if (name == 'hAlign') {
				switch (position[name]) {
					case 'left':	Element.setStyle(e, { 
										position: 'absolute', 
										left: 0 
									});
									break;
					case 'center':	Element.setStyle(e, { 
										position: 'absolute', 
										left: '50%', 
										marginLeft: ((dimensions.width / 2) * -1) + 'px' 
									});
									break;
					case 'middle':	Element.setStyle(e, { 
										position: 'absolute', 
										left: '50%', 
										marginLeft: ((dimensions.width / 2) * -1) + 'px' 
									});
									break;
					case 'right':	Element.setStyle(e, { 
										position: 'absolute', 
										right: 0 
									});
									break;
				}
			} else if (name == 'vAlign') {
				switch (position[name]) {
					case 'top':		Element.setStyle(e, { 
										position: 'absolute', 
										top: 0 
									});
									break;
					case 'center':	Element.setStyle(e, { 
										position: 'absolute', 
										top: '50%', 
										marginTop: ((dimensions.height / 2) * -1) + 'px' 
									});
									break;
					case 'middle':	Element.setStyle(e, { 
										position: 'absolute', 
										top: '50%', 
										marginTop: ((dimensions.height / 2) * -1) + 'px' 
									});
									break;
					case 'bottom':	Element.setStyle(e, { 
										position: 'absolute', 
										bottom: 0 
									});
									break;
				}
			}
		}
	}
	return e;
}