// espace
// **** espace ***

// Adapted from http://www.codewalkers.com/c/a/Miscellaneous-Code/JavaScriptPHP-US-phone-number-validation/
function check_usphone(field) {

	var element = document.getElementById(field)
	var number = element.value

	if (number == '') {
		return true
	}

	if (!number.match(/^[ ]*[(]{0,1}[ ]*[0-9]{3,3}[ ]*[)]{0,1}[-]{0,1}[ ]*[0-9]{3,3}[ ]*[-]{0,1}[ ]*[0-9]{4,4}[ x0-9]*$/)) {
		element.focus()
		alert('Phone number format is (www) xxx-yyyy zzz')
		return false
	}
	else {
		return true
	}
} 

// Verify a URL
function check_url(field) {
	var element = document.getElementById(field)
	var url = element.value

	if (url == '') {
		return true
	}

	if ((url.substring(0, 7) != 'http://') &&
			(url.substring(0, 8) != 'https://')) {
		element.focus()
		alert('The web address must start with http:// or https://')
		return false
	}
	else {
		return true
	}	
}

// 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 isMac = (ua.indexOf('maci') != -1);
var isIE = (ua.indexOf('msie') != - 1);
var isMacIE = isIE && isMac;

// 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]  Days to expire 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) {
	var today = new Date();
	today.setTime(today.getTime());

	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
		var expires_date = new Date(today.getTime() + expires);
		var str = expires_date.toGMTString();
		var expires_str = str.substr(0, 7) + '-' + str.substr(8, 3) + '-' + str.substr(12);
	}

	cookie = name + "=" + escape(value) +
						((expires_date) ? ";expires=" + expires_str : "") +
						((path) ? ";path=" + path : "") +
						((domain) ? ";domain=" + domain : "") +
						((secure) ? ";secure" : "");
	document.cookie = cookie;
}

/*
 * 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 num = field.value.replace('$', '').replace(/,/g, '');

  if (num == '') {
		num = 0;
  }

	if (!isFloat(num)) {
		alert(name + ' must be a number between ' + min + ' and ' + max)
		field.focus()
		return(true)
	}
	if (num < min) {
		alert(name + ' must be at least ' + min)
		field.focus()
		return(true)
	}
	if (num > max) {
		alert(name + ' must be less than or equal to ' + max)
		field.focus()
		return(true)
	}

	return(false)
}

// Return true if parm is a float
// Can include a leading dollar sign
function isFloat(str) {
	return(str == String(str).match(/[+-]{0,1}[$]{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
         alert('Invalid date. Use one of the following formats:\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
	}
}

// Return the selected value
function get_select_value(select) {
	return(select.options[select.selectedIndex].value)
}

// 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;
}

function exportTable(id) {
  var html = document.getElementById(id).innerHTML
  document.getElementById('table_html').value = html
  document.getElementById('myForm').submit()
}

// Show a popup (DIV)
function show_popup(id) {
	var el = document.getElementById(id);

	// Change the parent so this will work in IE7 (weird problem?!?)
	//document.body.appendChild(el);
	//document.getElementById('myForm').appendChild(el);

	// Make draggable if we have scriptaculous
	// On Macs, if the popup has Flash, the Flash itself is draggable (you can't click in it?!?)
	if (!isMac) {
		try {	new Draggable(id) } catch (err) { }
	}

	// Fade out the page
	var scrolled = getScrollXY();
	fade_page();

	/* Advanced styles */
	el.style.MozBorderRadius = '8px';
	el.style.webkitBorderRadius = '8px';
	el.style.MozBoxShadow = '5px 5px 5px #444';
	el.style.webkitBoxShadow = '5px 5px 5px #444';
	el.style.boxShadow = '5px 5px 5px #444';
	el.style.filter = 'progid:DXImageTransform.Microsoft.Shadow(color=#444444,direction=135)';
	el.style.display = 'block';
	el.style.position = 'absolute';
	el.style.zIndex = 100;

	/* Title... if it exists */
	if (el.childNodes[1]) {
		el.childNodes[1].style.MozBorderRadius = '7px 7px 0 0';
		el.childNodes[1].style.webkitBorderRadius = '7px 7px 0 0';
	}

	// Window size
  var width = 0, height = 0;
  if (typeof(window.innerWidth) == 'number') {
		width = window.innerWidth;
		height = window.innerHeight;
  }
	else if (document.documentElement && (document.documentElement.clientWidth)) {
		width = document.documentElement.clientWidth;
		height = document.documentElement.clientHeight;
  }
	else if (document.body && (document.body.clientWidth)) {
		width = document.body.clientWidth;
		height = document.body.clientHeight;
  }

	// Element size
	var w = 0, h = 0;
	if (el.style.pixelWidth) {
		w = el.style.pixelWidth;
		h = el.style.pixelHeight;
	}
	else {
		w = el.offsetWidth;
		h = el.offsetHeight;
	}

	// Position the popup
	el.style.top = (scrolled[1] + (height - h) / 2) + 'px';
	el.style.left = (scrolled[0] + (width - w) / 2) + 'px';

	// Set the focus to the first input field (after it has appeared)
	setTimeout("var inputs = $$('#" + id + " input'); if (inputs.length > 0) { try { inputs[0].focus() } catch(err) {} }", 250);

	// Fade in... handle IE and no scriptaculous
	el.style.display = 'none';
	try {
		Effect.Appear(el, {duration: 0.2});
	}
	catch (err) {
		el.style.display = 'block';
	}

	// In case 'display: block' is set in the style sheet
	setTimeout("document.getElementById('" + id + "').style.display = 'block'", 200);

	return(false);
}

// Hide a popup (DIV) that was displayed with show_popup()
// The DIV should have CLASS=POPUP (which sets the z-index, position, display, etc.
function hide_popup(id) {
	document.getElementById(id).style.display = 'none';
	unfade_page();
}

// Darken the page
function fade_page() {
	var scrolled = getScrollXY();

  var back = document.createElement('div');
  back.style.zIndex = 99
  back.id = 'x_fade_page';
  back.style.position = 'absolute';
	back.style.top = scrolled[1] + 'px';
	back.style.left = scrolled[0] + 'px';
  back.style.height = '100%';
  back.style.width = '100%';
  back.style.backgroundColor = '#fff';
  back.style.opacity = '0.80';
  back.style.filter += ("progid:DXImageTransform.Microsoft.Alpha(opacity=80)");
  document.body.appendChild(back);

	return(false);
}

// Un-fade the page
function unfade_page() {
	document.body.removeChild(document.getElementById('x_fade_page'));
	return(false);
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;

	// Netscape compliant
  if (typeof(window.pageYOffset) == 'number') {
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	}

	// DOM compliant
	else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} 

	// IE6 standards compliant mode
	else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}

	return(new Array(scrOfX, scrOfY));
}

// Call to convert ENTER to TAB
function enterToTab() {
	$$('input').each(function(input) {
		Event.observe(input, 'keydown', enter2Tab);
	} )
}

// PRIVATE
function enter2Tab(e) {
	if (e.keyCode == 13) {
		Event.stop(e);

		var all = Form.getElements('myForm');
		var found = false;

		// Look for the first after the current
		for (var i=0; i<all.length; i++) {
			if (all[i].id == this.id) {
				found = true;
			}

			if (found) {
				if (all[i+1].type != 'hidden') {
					all[i+1].focus();
					all[i+1].select();
					return;
				}
			}
		}

		// Look for the first
		for (var i=0; i<all.length; i++) {
			if (all[i].type != 'hidden') {
				all[i].focus();
				all[i].select();
				return;
			}
		}
	}
}

// Based on http://tuckey.org/textareasizer/
function autosize_ta(ta, min) {
	var t = document.getElementById(ta);
	var s = t.value;
	if (s) {
		var h = 1;
		var l = 0;
		while (l > -1) {
			l = s.indexOf("\n", l+1);
			h++;
		}
		var o = Math.round(s.length / (t.cols-1));
		var c = (h > o ? h : o);
		if (c < min) {
			c = min;
		}
		t.rows = c;
	}
}

function toggle_display(id) {
	var el = document.getElementById(id);
	el.style.display = (el.style.display == 'none' ? 'block' : 'none');
	return(false);
}

function twistee(triangle, content) {
	if ($(content).style.display == 'none') {
		$(content).style.display = 'block';
		triangle.innerHTML = '&#9660;';
		// triangle.scrollTo();
	}
	else {
		$(content).style.display = 'none';
		triangle.innerHTML = '&#9658;';
	}

	return(false);
}

