/* javascript functions in this file are:  
	1.	FormatDate(DateString) - returns date in MM/DD/YYYY format
	2.  FormatPastDate(DateString) - not quite sure how this is different from #1....
	3.  FormatTime(TimeString) - returns time in HH:MM TT format
	4.	checkzip(zipString) - returns t/f for valid zipcode
	5.	isPhone(areaCodeObject, phoneObject1, phoneObject2) - returns t/f for valid phone #
	6.  y2k(number) - returns y2k compliant date
	7.  isDate(datestring) - returns t/f if in valid date format
	8.	isInteger (theObject) - returns t/f if form object is sent
	9.	isInteger (integerString) - returns t/f if string value is sent
	10. displayPopup(url,name,height,width,evnt) 
	11.	closePopup() 
	12.	ErrorMessage(theForm, theObject, theValue, theMessage) - alerts the message & returns focus to the object
	13.	isEmail(email_value) - returns t/f
	14. daysElapsed(date1,date2)  - returns integer difference of (date1 - date2)
	15.	DayOfWeek(day,month,year) - returns integer 
	16.	isRegTime(object_value) - returns t/f
	17.	stripSpaces(string) - removes all spaces from beginning and end of string
	18. addNew(whichOne, theForm, extra) - prompts for the quantity to be added
	19. addListGraphic(whichOne, section, theForm) - same as addNew, but when dealing w/ multiples
	20. goBack(where) - sets the location to the text string sent
*/
function FormatDate(DateString)
	{
	var theDate =  new Date(DateString)	
	var theYear = theDate.getYear()

	if (parseInt(theYear,10) < 1000)
	{
		if (parseInt(theYear,10) < 100)
		{
			theYear += 2000
		}
		else  
		{
			theYear += 1900
		}
	}
	var theDay = theDate.getDate()
	if (theDay < 10)
		theDay = "0" + theDay;
	var theMonth = theDate.getMonth() + 1
	if (theMonth < 10)
		theMonth = "0" + theMonth;
	return theMonth + "/" + theDay + "/" + theYear
	}

function FormatPastDate(DateString)
	{
	var theDate =  new Date(DateString)	
	var theYear = theDate.getYear()

	if (parseInt(theYear,10) < 1000)
	{
		if (parseInt(theYear,10) < 01)
		{
			theYear += 2000
		}
		else  
		{
			theYear += 1900
		}
	}
	var theDay = theDate.getDate()
	if (theDay < 10)
		theDay = "0" + theDay;
	var theMonth = theDate.getMonth() + 1
	if (theMonth < 10)
		theMonth = "0" + theMonth;
	return theMonth + "/" + theDay + "/" + theYear
	}

function FormatTime(TimeString)
{
	var theHour = "";
	var theSuffix = "";
	var theTime = "";
	var theMinutes = "";

	if (TimeString.charAt(1) == ":")
		theHour = parseInt(TimeString.substring(0,1),10)
	else
		theHour = parseInt(TimeString.substring(0,2),10)
			
	if (theHour > 12)
	{
		theHour = theHour - 12;
		theSuffix = " PM"
	}
	else
	{
		theSuffix = " AM"
	}
	if (theHour < 10)
		theHour = "0" + theHour;

	if (TimeString.charAt(1) == ":")
		theMinutes = TimeString.substring(2,TimeString.length)
	else
		theMinutes = TimeString.substring(3,TimeString.length)

	theTime = theHour + ":" + theMinutes + theSuffix;
	return theTime;
}

function checkzip(object_value)
// accepts the following formats.
// 12345
// 12345 6789
// 12345-6789
    {
    if (object_value.length == 0)
	    return false;	
		
    if (object_value.length != 5 && object_value.length != 10)
	    return false;

	// make sure first 5 digits are a valid integer
	if (object_value.charAt(0) == "-" || object_value.charAt(0) == "+")
        return false;

	if (isIntegerString(object_value.substring(0,5)) == false)
		return false;

	if (object_value.length == 5)
		return true;
	
	// make sure

	// check if separator is either a'-' or ' '
	if (object_value.charAt(5) != "-" && object_value.charAt(5) != " ")
        return false;

	// check if last 4 digits are a valid integer
	if (object_value.charAt(6) == "-" || object_value.charAt(6) == "+")
        return false;
	
	if (isIntegerString(object_value.substring(6,10)) == true)
		return true;
	
	return false;
}

function isPhone(areaCodeObject, phoneObject1, phoneObject2)
{
	 var areaCode = areaCodeObject.value;
	 var phone1 = phoneObject1.value;
	 var phone2 = phoneObject2.value;
		 
     if( isNaN(areaCode) || isNaN(phone1) || isNaN(phone2))
		return false;

	 if ((areaCode != "") || (phone1 != "") || (phone2 != ""))
	 	if ((areaCode == "") || (phone1 == "") || (phone2 == ""))
			return false;
		else if (areaCode.length < 3 || phone1.length < 3 || phone2.length < 4)
			return false;
	 return true;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function isDate (DateVal) {
 // checks if date passed is valid
 // will accept dates in following format:
 // isDate(dd,mm,ccyy), or
 // isDate(dd,mm) - which defaults to the current year, or
 // isDate(dd) - which defaults to the current month and year.
 // Note, if passed the month must be between 1 and 12, and the
 // year in ccyy format.


    if (DateVal.length <= 0)
        return true;
	

    //Returns true if value is a date in the mm/dd/yyyy format
    isplit = DateVal.indexOf('/');

    if (isplit == -1 || isplit == DateVal.length)
    	return false;
	
		var month = DateVal.substring(0, isplit);
		isplit = DateVal.indexOf('/', isplit + 1);
		var day = DateVal.substring((month.length +1), isplit);
		var year = DateVal.substring(isplit+1);
		///I know this is a hack, but it will make this year function work until 2025 
		if(year.length == 2)
			if(year > 25)
				year = "19" + year;
			else
				year = "20" + year;

     var today = new Date();
     year = ((!year) ? y2k(today.getYear()):year);
     month = ((!month) ? today.getMonth():month-1);
     if (!day) return false
     var test = new Date(year,month,day);
     if ( (y2k(test.getYear()) == year) &&
          (month == test.getMonth()) &&
          (day == test.getDate()) )
         return true;
     else
         return false
 }

function isInteger (theObject) 
{	
	if ((isNaN(theObject.value)) || (theObject.value.indexOf(".") > -1) || (theObject.value.indexOf("-") > -1))
	{
		return false;
	}
	return true;
}

function isIntegerString (theObjectValue) 
{	
	if ((isNaN(theObjectValue)) || (theObjectValue.indexOf(".") > -1) || (theObjectValue.indexOf("-") > -1))
	{
		return false;
	}
	return true;
}

version4 = false
if(navigator.appVersion.charAt(0) == "4") version4 = true

function displayPopup(url,name,height,width,evnt)
{
	var properties = "toolbar=0,location=0,height="+height
	properties = properties+",width="+width
  	if(evnt != null)
	{
		if(navigator.appName == "Microsoft Internet Explorer")
		{
			properties = properties+",left="+(evnt.screenX + 10)
			properties = properties+",top="+(evnt.screenY + 10)
		}else
		{ // Navigator coordinates must be adjusted for scrolling
			properties = properties+",left="+(evnt.screenX - pageXOffset + 10)
			properties = properties+",top="+(evnt.screenY - pageYOffset - height)
		}
	}
	popupHandle = open(url,name,properties)
}

function closePopup()
{
	if(popupHandle != null && !popupHandle.closed) popupHandle.close()
}

function ErrorMessage(theForm, theObject, theValue, theMessage)
{
	alert(theMessage);
	theObject.focus();
	theObject.select();
}

/*
Advanced Email Check credit-
By Website Abstraction (www.wsabstract.com)
Over 200+ free scripts here!
http://www.wsabstract.com/script/script2/acheck.shtml

This script checks that the email meets the following conditions

- Contains a least one character procedding the "@"
- Contains a "@" following the procedding character(s)
- Contains at least one character following the "@", followed by a dot (.), 
  followed by either a two character or three character string (a two character
  country code or the standard three character US code, such as com, edu etc)

*/

function isEmail(email_value)
{
	var filter=/^.+@.+\..{2,3}$/
	if(email_value != "")
	{
		if (!(filter.test(email_value)))
		{
			return false;
		}
	}
	return true;
}
	
function daysElapsed(date1,date2) {
	var year1 = y2k(date1.getYear()), year2 = y2k(date2.getYear());
	//see above note on hacking...
	if( parseInt(year1) < 1925)
		year1 = parseInt(year1) + 100;
	
	if( parseInt(year2) < 1925)
		year2 = parseInt(year2) + 100;

     var difference =
         Date.UTC(year1,date1.getMonth(),date1.getDate(),0,0,0)
       - Date.UTC(year2,date2.getMonth(),date2.getDate(),0,0,0);
	 return difference/1000/60/60/24;
 }

//pass it day, month, year as integers and it'll return an integer (1-7)
function DayOfWeek(day,month,year) {
    var a = Math.floor((14 - month)/12);
    var y = year - a;
    var m = month + 12*a - 2;
    var d = (day + y + Math.floor(y/4) - Math.floor(y/100) +
             Math.floor(y/400) + Math.floor((31*m)/12)) % 7;
    return d + 1;
}

function isRegTime(object_value)
{
    //Accepts the following format:  hh:mm 
    if (object_value.length == 0)
        return true;

	var isplit = object_value.indexOf(':');
	if (isplit == -1 || isplit == object_value.length)
		return false;

    var sHour = object_value.substring(0, isplit);
	var sMin = object_value.substring(isplit+1, object_value.length);

	//check for non-numerics
	if (isNaN(sHour) || isNaN(sMin))
		return false

	//check hour
	if (sHour < 1 || sHour > 12)
		return false;

	//check minutes
	if (sMin < 0 || sMin > 60)
		return false;

    return true;
}

function stripSpaces(x) {
     while (x.substring(0,1) == ' ') x = x.substring(1);					  //remove from front
     while (x.substring(x.length-1) == ' ') x = x.substring(0, x.length-1); //remove from end
	 return x;
 }


function addNew(whichOne, theForm, extra)
{
	var ans = prompt("How many new "+ whichOne + extra+" would you like to add?", "");
	if(ans)
	{	
		theForm.elements["new"+whichOne].value = ans;
		theForm.submit()
	}
}


function addListGraphic(whichOne, section, theForm)
{
	var secAlert = section
	if (secAlert != "") secAlert = " to Section " + secAlert;
	var ans = prompt("How many new "+ whichOne + " would you like to add to section " + section +"?", "");
	if(ans)
	{	
		theForm.ref.value = whichOne.substring(0,1).toLowerCase();
		theForm.section.value = section;
		theForm.cnt.value = ans
		theForm.submit()
	}
}

//	20. goBack(where) - sets the location to the text string sent
function goBack(where){location = where;}

// -->

function deleteOptions(whichControl)
{
	for(var i = whichControl.length; i >= 0; i--)
		whichControl.options[i] = null;
}


function refill(matchID, theSelect, theArray, showAll, txtAll, valAll, fallOut, matchIndex, txtIndex, valIndex)
{
	var i, theTxt;
	if (showAll)
		theSelect.options[0] = new Option(txtAll, valAll);
		
	for (i = 0; i < theArray.length; i++)
	{
		if(theArray[i][matchIndex] == matchID) {
			theSelect.options[theSelect.length] = new Option(theArray[i][txtIndex], theArray[i][valIndex]);
		}
		else if (fallOut && theArray[i][matchIndex] > matchID)
			break;
	}
}	
function validateRequired(frmObject, name) {
	if(frmObject.type == "text" || frmObject.type == "password") {
		if (stripSpaces(frmObject.value) == '') {
			alert("Please enter a valid " + name +".");
			frmObject.focus();
			frmObject.select();
			return false;
		}
	} else if (frmObject.type == "select-one") {
		if (frmObject.selectedIndex <= 0) {
			alert("Please select a" + name +".");
			frmObject.focus();
			return false;
		}
	}
	return true;

}

function checkLength(theTxtArea, maxLen) {
	if(theTxtArea.length > maxLen) {
		alert("Maximum length of the field has been exceeded.  Only "& maxLen &" characters allowed.");
		theTxtArea.value = theTxtArea.substring(0, maxLen);
	}
}

function moveBetweenFields(RemoveBox, ReceiveBox)
{	// Move elements from one multiselect list to the other
	var arySelected = new Array();			// Array of selected elements
	var selected = false;
	var alreadyAdded;

	for (var i=0;i<RemoveBox.length;i++) {
		if (RemoveBox.options[i].selected==true)
		{	// Get all selected clients to be moved
			arySelected [arySelected.length] = new Array(RemoveBox.options[i].value, RemoveBox.options[i].text);
			selected = true;
		}
	}
	
	if ((!selected)&&(RemoveBox==RemoveBox.form.dnuAvailClientID))
	{	// Make sure at least one client was selected
		alert("A client must be selected from the list of all available clients to move them to assigned.");
		return false;
	}	else if ((!selected)&&(RemoveBox==dnuClientID))	{	
		// Make sure at least one client was selected
		alert("A client must be selected from the list of assigned elements to remove them.");
		return false;
	}
	
	for (j=0;j<arySelected.length;j++)	{		// Each selected client
		for (i=0;i<RemoveBox.length;i++) {	 	// Each available client
			if (arySelected[j][0] == RemoveBox.options[i].value)
			{	
				RemoveBox.options[i] = null;
				ReceiveBox.options[ReceiveBox.length] = new Option(arySelected[j][1], arySelected[j][0]);
				break;
			}
		}
	}
}

