// Useful scripts for all intranet pages
function formatPhone(num){
	var strEdit = num.replace(/[^\d]/g,'');
	
	_return="(";
	var ini = strEdit.substring(0,3);
	_return+=ini+") ";
	var st = strEdit.substring(3,6);
	_return+=st+"-";
	var end = strEdit.substring(6,10);
	_return+=end;
  return _return; 

}
function formatSSN(ssn){
	var strEdit = ssn.replace(/[^\d]/g,'');
	_return = '';
	var ini = strEdit.substring(0,3);
	_return += ini;
	if(strEdit.length >= 3){
		_return+="-";
		var ini = strEdit.substring(3,5);
		_return += ini;
		if(strEdit.length>=5){
			_return+="-";
			var ini = strEdit.substring(5,9);
			_return += ini;
		}
	}
	return _return;
	
}
function formatDateValue(num){
	var strEdit = num.replace(/[^\d]/g,'');
	_return = '';
	
	var ini = strEdit.substring(0,2);
	_return += ini;
	if (strEdit.length >= 2) _return+="/";
	var st = strEdit.substring(2,4);
	_return += st;
	if (strEdit.length >= 4) _return+="/";
	var end = strEdit.substring(4,8);
	_return+=end;
  return _return; 

}

function checkBoxSelectAll(elm){
	if(elm.length){
		for(var j=0;j < elm.length;j++){
			elm[j].checked = true;
		}
	}
	else{
		elm.checked = true;
	}
}
function checkBoxDeSelectAll(elm){
	if(elm.length){
		for(var j=0;j < elm.length;j++){
			elm[j].checked = false;
		}
	}
	else{
		elm.checked = false;
	}
}

// expands the dashboard

function expandDashboard(){
	dash = document.getElementById('myDashboard');
	dsElms = document.getElementById('dashScroll');	
	
	// expand the items
	if (dsElms.style.height == '65px'){
		dsElms.style.height = '300px';
	}
	// contract
	else{
		dsElms.style.height = '65px';
	}
	
}
// toggles elements on or off display-wise

function toggleElm(id){
	myElm = document.getElementById(id);
	
	if (myElm){
		if(myElm.style.display == 'inline'){
			myElm.style.display = 'none';
		}
		else{
			myElm.style.display = 'inline';
		}
	}
}

function toggleHelp(){
	myDiv = document.getElementById('helpDiv');
	myOvr = document.getElementById('helpOverlay');
	
	if (myDiv){
		if (myDiv.style.display == 'inline'){
			myDiv.style.display='none';
			myOvr.style.display='none';
			
		}
		else{
			// retrieve sizing values
			pgSize = getPageSize();
			pgScroll = getPageScroll();
			
			// position the help dialog
			myDiv.style.top = pgScroll[1]+50;
			myDiv.style.left = 70;
			myDiv.style.display='inline';
			
			// set the overlay layer to the right size
			myOvr.style.width = pgSize[0];
			myOvr.style.height = pgSize[1];
			myOvr.style.display='inline';
			
		}
	}
}

// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}


// checkShortcut()
// tests the current key release to see if it matches a shortcut
// if it does then do something else do nothing
// also used to cancel the enter key from submitting a form.
function checkShortcut(){
	
	if (disableEnter){
		if (self.event.keyCode!=13) return;
		self.event.returnValue= false; 
	}
}


function disableButton(theButton)
		{
		 theButton.value="Processing...";
		 theButton.disabled = true;
		 theButton.form.submit();
		}
	
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);
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	// keyboard shortcuts can go here now...
	
}


//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }
	

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate2(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		errors+="The date format should be : mm/dd/yyyy"
		return false 
	}
	if (strMonth.length<1 || month<1 || month>12){
		errors+="Please enter a valid month<br/>"
		return false 
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		errors+="Please enter a valid day<br/>"
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		errors+="Please enter a valid 4 digit year between "+minYear+" and "+maxYear+"<br/>"
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		errors+="Please enter a valid date"
		return false
	}
return true
}	/* ColdFusion List Functions
   These functions manipulate lists just list ColdFusion does.
   (c) Digital Crew
   Happy Christmas. Knock yourself out.
   email: topper@digital-crew.com
   web: www.digital-crew.com   /   www.cftopper.com
*/
function listFind(c,n,d)
{
	if(arguments.length<3)d=",";
	var e = c.split(d);
	for(var i=0;i<c.length;i++) if( e[i]==n ) return i+1;
	return 0;
}
function listPrepend(c,n,d)
{
	if(arguments.length<3)d=",";
	return n+(c!=""?(d+c):"");
}
function listAppend(c,n,d)
{
	if(arguments.length<3)d=",";
	return (c!=""?(c+d):"")+n;
}
function listDeleteAt(c,p,d)
{
	if(arguments.length<3)d=",";
	var e = c.split(d);
	if(p<=e.length)
	{
		var n="";
		for(var i=0;i<p-1;i++) n=n+e[i]+d;
		for(var i=p;i<e.length;i++) n=n+e[i]+d;
		return (n.length<1 || n.charAt(n.length-1)!=d)?n:n.substring(0,n.length-1);
	}
	return c;
}
function listGetAt(c,p,d)
{
	if(arguments.length<3)d=",";
	var e = c.split(d);
	if( p >= 1 && p <= e.length )
	{
		return e[p-1];
	}
	alert("Out of range");
	return "";
}
function listSetAt(c,p,v,d)
{
	if(arguments.length<4) d=",";
	var e = c.split(d);
	if( p >= 1 && p <= e.length )
	{
		e[p-1] = v;//set the value
		//rebuild the string
		for( var i=0,c=""; i < e.length; i++ )
			c = (c!=""?(c+d):"")+e[i];
	}
	else alert("listSetAt: Index " + p + " is Out of range");
	return c;
}
function listInsertAt(c,p,v,d)
{
	if(arguments.length<4) d=",";
	var e = c.split(d);
	if( p >= 1 && p <= e.length+1 )
	{
		e.splice( p-1, 0, v );//insert the value
		//rebuild the string
		for( var i=0,c=""; i < e.length; i++ )
			c = (c!=""?(c+d):"")+e[i];
	}
	else alert("listSetAt: Index " + p + " is Out of range");
	return c;
}
function listLen(c,d)
{
	if( c == "" ) return 0;
	if(arguments.length<2)d=",";
	return c.split(d).length;
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}
function checkCookie()
{
username=getCookie('username');
if (username!=null && username!="")
  {
  alert('Welcome again '+username+'!');
  }
else
  {
  username=prompt('Please enter your name:',"");
  if (username!=null && username!="")
    {
    setCookie('username',username,365);
    }
  }
}



/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

	if (arguments[0]==''){return '';}
	
	/* if they entered a string that didnt have slashes and expected it to work then rewrite it with slashes.  only works with mmddyyyy entered */
	if (arguments[0].length == 8 && arguments[0].match(/[^\d]/g,'') == null){
		arguments[0] = formatDateValue(arguments[0]);
	}
		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
