//
// Project:		Short WAPP
// Filename:	cs_function.js
//
// 04/13/99 - SCC - Created. These functions are those that are common to every page for cs validation.
//				  - Ported doChange(), unaltered.
// 04/15/99 - SCC - Port checkThreePartDate(), unaltered.
//				  - Port validYear(), changed name.
// 05/05/99 - SCC - Port stripFun(),stripInFun(),filterNum(), unaltered.
// 05/11/99 - SCC - Port filterString(),upFirstChar(),stripGremlins(). Altered names (removed _'s), plus
//					slight mod to filterString to catch undefined parameter (exceptions)
//				  - Add properField(), based on old properFun() but uses filterString() +.. routines.
// 05/14/99 - SCC - Port isPostal(),isNum(),isChar(). Slight mods.
// 05/17/99 - SCC - Add monthsFromYM().
//				  - Port isSin(), change name.
//				  - Port do_Other(), unaltered.
// 05/20/99 - SCC - Port validateNum(),formatRealNum(),formatInteger(),commaFmt(), unaltered.
//				  - Port tally(), changed name.
// 05/30/99 - SCC - Port trim(), changed name.
// 09/09/99 - SCC - Add sizeOk to check field lengths in case onChange events don't fire.
//

// Page variables **************************************************************************************
var fieldsChanged = ',';	// Used with doChange(objName), is the list of fields to be updated to the db.

function TimeStamp() { dt=new Date(); return dt.getTime(); }

function formatPhoneNum(Field) {
	var sNum = "";
	var sNumOut = "";
	var nCounter = 0;
	var sNumbers = "0123456789";
		
	// first loop through the phone number and save only the numbers
	for (nCounter = 0; nCounter < Field.value.length; nCounter++) {
		if (sNumbers.indexOf(Field.value.charAt(nCounter)) > -1) {
			sNum += Field.value.charAt(nCounter);
		} 	
	}		
	if (sNum.length < 10) {
		alert("You must enter an area code");
		Field.focus();
	} else if (sNum.length > 10) {
		alert("You have entered too many numbers");
		Field.focus();
	} else {
		sNumOut = "(" + sNum.substring(0, 3) + ") " + sNum.substring(3, 6) + "-" + sNum.substring(6, 10);
	}
	Field.value = sNumOut;
}

// Page functions  **************************************************************************************
function doChange(objName) {
	var i = 0;
	var testMe = "";
	for (i=0;i<(doChange.arguments.length);i++) {
		testMe = "," + doChange.arguments[i] + ",";
		if (fieldsChanged.indexOf(testMe) == -1) {
			fieldsChanged = fieldsChanged + doChange.arguments[i] + ',';
			document.forms[0].ChangedFields.value = fieldsChanged;
		}
	}
	return true;
}

function do_Submit(url) {
	if (document.forms.length != 0) {
		if (do_Submit.arguments.length != 0)
			document.forms[0].nexturl.value = url;
		document.forms[0].submit();
		//top.location.replace(document.forms[0].action)
	}
	else
		top.location.replace(url);
		//window.location.href = url
	return true;
}

function isKeyDown_ctrlForPC_optForMac(evt) {
	var returnStr = false;
	var isIE = (navigator.userAgent.indexOf('MSIE') != -1);
	var isMAC = (navigator.appVersion.indexOf('Mac') != -1);
	if (isMAC) {	// Check for alt(option) Key //
		if (isIE)
			returnStr = window.event.altKey;
		else
			returnStr = evt.modifiers & Event.ALT_MASK;
	}
	else {			// PC: Check for control key ///
		if (isIE)
			returnStr = window.event.ctrlKey;
		else {
			//returnStr = evt.modifiers & Event.CONTROL_MASK;	// Causes crash in VPC/NAV ** SCC - Figure out why later! //
			//alert('evt.modifiers is |'+evt.modifiers+'|');
		}
	}
	//alert('isMAC=|'+isMAC+'|  returnStr=|'+returnStr+"|");
	return returnStr;
}


function dropDownVal(theStr) {
	//alert("the theStr called is "+theStr);
	if (!document.forms[0].elements[theStr])
		return '';
	else
		return document.forms[0].elements[theStr].options[document.forms[0].elements[theStr].selectedIndex].value;
}

function checkDrop(dropNameStr) {
	var thisDrop = dropDownVal(dropNameStr)
	//alert(dropNameStr+"\r"+thisDrop);
	if (thisDrop+""=="")
		return false;
	else 
		return true;
}

function checkText(objNameStr) {
	var thisTextObj = document.forms[0].elements[objNameStr];
	var thisTextVal = "";
	if (thisTextObj.value.length > 0)
		thisTextVal = stripinFun(thisTextObj.value,"abcdefghijklmnopqrstuvwwyzABCDEFGHIJKLMNOPQRSTUVWWYZ.,/;:<>'[{]}|-=_+1234567890!@#$%^&*()") + "";	// strip out nbsp spaces
	if (thisTextVal == "") {
		thisTextObj.focus();
		thisTextObj.select();
		return false;
	}
	else 
		return true;
}

function setStatus(theMsg) {
	window.status = theMsg;
	return true;
}

// THIS MAKES SURE THERE ARE VALUES FOR ALL THREE PARTS BEFORE ERROR CHECKING //
function checkThreePartDate(dayEle,monEle,yearEle,yearMin,yearMax) {
	//alert("monEle.value.length='"+monEle.value.length+"'\rdayEle.value.length='"+dayEle.value.length+"'\ryearEle.value.length='"+yearEle.value.length+"'");
	dayEle.value = stripinFun(dayEle.value,"0123456789");
	monEle.value = stripinFun(monEle.value,"0123456789");
	yearEle.value = stripinFun(yearEle.value,"0123456789");
	if (monEle.value.length > 0 && dayEle.value.length > 0 && yearEle.value.length > 0) {
		var monVal = parseInt(monEle.value,10);
		var dayVal = parseInt(dayEle.value,10);
		var yearVal = parseInt(yearEle.value,10);
		//alert("monVal='"+monVal+"'\rdayVal='"+dayVal+"'\ryearVal='"+yearVal+"'");
		if(validYear(yearEle,yearMin,yearMax)) {
			if(!validDate(dayVal,monVal,yearVal)) {
				alert('Invalid date, please correct');
				dayEle.value = '';
				monEle.value = '';
				yearEle.value = '';
				monEle.focus();
			}
			else
				return true;
		}
		else {
			alert("Invalid year, please correct");
			yearEle.value = '';
			yearEle.focus();
		}
	}
	else
		return false;	
}

function validDate(ddInt,mmInt,yyInt) {
	var returnBol = true;
	var m30Str = "|4|6|9|11|";
	var febInt = 28;
	var tempVar = 0;
	
	if (isNaN(yyInt))
		returnBol = false;
	else {
		if (yyInt < 1800)  		// Handle all 2 digit dates, force to 4 digits //
			tempVar = 1900 + yyInt;
	}
	if ((yyInt % 4) == 0) {		// 29 days in February calc //
		if ((yyInt % 100) == 0) {
			if ((yyInt % 400) == 0)
				febInt = 29;
		} 
		else 
			febInt = 29;
	}
	if ((mmInt!="")&&( mmInt>12)) {
		returnBol = false;
    } else if ((mmInt!="")&&(mmInt == 2)) {
		if ((ddInt!="")&&(ddInt > febInt)) {
			returnBol = false;
		}
	} else if (m30Str.indexOf("|"+mmInt+"|")!=-1) {
		if ((ddInt!="")&&(ddInt > 30)){
			returnBol = false;}
	} else {
		if ((ddInt!="")&&(ddInt > 31)){
			returnBol = false;}
	}
	return returnBol;
}

function validYear(yEle,minInt,maxInt) {

	var userStr = stripinFun(yEle.value,"0123456789");
	var todayDte = new Date();
	var centryStr = todayDte.getYear();
	if (userStr.length==0)
		return true;
	if (userStr.length==1||userStr.length==3||userStr.length>4) {
		//alert("Not right size");
		return false;
	}
	if ((parseInt(centryStr),10) < 100 && (parseInt(centryStr),10) != 0) {
		centryStr = "19";
	} else {
		centryStr = "20";
	}
	if (userStr.length==2) 
		userStr = centryStr + userStr;

	if ((parseInt(userStr,10) >= minInt) && (parseInt(userStr,10) <= maxInt)) {
		yEle.value = userStr;
		return true;
	}
	
	return false;

}

function filterNum(theNum) {
// REMOVE ALL NON-NUMERIC CHARS
	var hasDecimal = false;
	var minusStr = "";
	var result = "";
	var theChar = "";
	for(i=0;i<=theNum.length;i++) {
		theChar = theNum.charAt(i);
		if(theChar==".") {
			if (hasDecimal) {
				return minusStr + result;
			} else {
				hasDecimal = true;
				result = result + theChar;
			}
		}
		else if(theChar=="-") {
			minusStr = "-";
		}
		else if(theChar>="0" && theChar<="9") {
 			result = result + theChar;
		}
	}
	return minusStr + result;
}

function stripFun (s, bag) {
	var i;
    var returnString = "";

    // Search through string's characters one by one.
    // Strip out characters that are in bag

    for (i = 0; i < s.length; i++) {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag 
// from string s.

function stripinFun (s, bag) {
	var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++) {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}

function upFirstChar(instr) {
	
	var i = 0; //For-loop variable counter
	var j = ""; //Character holder
	var newstr = ""; //Return variable
	var new_word = false //Used to check if there is a gap and the next word needs to be upCased.
	
	for ( i=0 ; i < instr.length ; i++ ) {
		j = instr.charAt(i);
		
		if ((i == 0) || (new_word == true))
			j = j.toUpperCase();
		else
			j = j.toLowerCase();
			
		//Check to see that we are not at a new word and need to upcase the first character
		if (j == " ")
			new_word = true;
		else
			new_word = false;
		
		newstr = newstr + j;
	}
	return newstr;
}

function stripGremlins(str) {
	//Used to strip ASCII characters ( 0 to 12 ) AND ( 14 to 31 ) AND ( 127 to 255 )
	var i = 0;
	var j = "";
	var newstr = "";
	var LF = unescape("%0A");
	var CR = unescape("%0D");
	for ( i=0 ; i < str.length ; i++ ) {
		j = str.charAt(i);
		if ( ( j == LF) || ( j == CR ) || ((j >= " ") && ( j <= "~")) )
			newstr = newstr + j;
	}
	return newstr;
}

function filterString(in_string,keep_Alpha,keep_Num,exceptions) {
	// MultiPurpose String Filter
	// Capable of filtering any specified characters

	var i = 0; //for loop counter
	var j = ""; //character holder
	var newstr = ""; //return variable	
	
	if (exceptions + "" == 'undefined')
		exceptions = "";
	
	//Boolean expressions for testing char-type initialized to false
	var is_alpha = false;
	var is_num = false;
	var is_except = false;
	
	//Remove the really nasty chars using strip_Gremlins(passing a string) 
	in_string = stripGremlins(in_string);

	//Create the new string to return according to parameters
	for ( i=0 ; i < in_string.length ; i++ ) {

		//reset the testing boolean values for the next iteration through the loop	
		is_alpha = false;
		is_num = false;
		is_except = false;

		j = in_string.charAt(i);
		
		// Test the data type
		if (exceptions.indexOf(j) != -1) //Then it is an exception character
			is_except = true;
		else if ( ((j >= "A") && (j <= "Z")) || ((j >= "a") && (j <= "z")) ) 
			is_alpha = true;
		else if ((j >= "0") && (j <= "9"))
			is_num = true;
		 
		//Apply the correct method
		if (is_except)
			newstr = newstr + j;
		else if ((keep_Alpha == true) && (is_alpha == true)) 
			newstr = newstr + j;
		else if ((keep_Num == true) && (is_num))
			newstr = newstr + j;
	}
	//done
	return newstr;
}

function properField(textElement,keepNumbers,exceptions) {
	var myStr = textElement.value;
	if (myStr == '')
		return true;

	if (exceptions+"" == 'undefined')
		exceptions = '';
	exceptions += " '.";		// Accept spaces, dots,single quotes (ie O' Reilly)//
		
	myStr = filterString(myStr,true,keepNumbers,exceptions);
	myStr = upFirstChar(myStr);
	textElement.value = myStr;
	return true;
}

function isNum(inString)  {
	if(inString.length!=1) 
		return false;
	var refString="1234567890";
	if (refString.indexOf(inString,0) == -1) 
		return false;
	return true;
}

function isChar(inString)  {
	if(inString.length!=1) 
		return false;
	var refString="abcdefghijklmnopqrstuvwxyzABCEDFGHIJKLMNOPQRSTUVWXYZ";
	if (refString.indexOf(inString,0) == -1) 
		return false;
	return true;
}

function isPostal(theObject) {
	// 02/16/99 - SCC - Modified to not show modal error when someone clears a postal code
	// 				    (ie - sends postEle.value of "")
	var a = theObject.value;
	var b = "";
	var u = "";
	var numString="1234567890";
	var failed = false;
	
	a = trim(a);
	var x = a.length;
	a = filterString(a, true, true, '')
	if (a.length < 1) {
		if (a.length == x) {
			return true;
		} else {
			return false;	
		}
	}
	for(i=0;i<=5;i++) {
		var u = a.charAt(i);
		
		if (i==1||i==3||i==5) {
			if (!isNum(u)) 
				failed=true;
		} 
		else {
			if (isChar(u)) 
				u=u.toUpperCase();
			else 
				failed=true;
		}
		var b = b + u;
	}

	b = b.substring(0,3)+" "+b.substring(3,6);

	theObject.value = b;

	return !(failed);
}

function monthsFromYM(yearObject,monthObject) {
	var totmInt = 0;

	if (yearObject.selectedIndex != 0 && monthObject.selectedIndex != 0) {
		totmInt = (parseInt(monthObject.options[monthObject.selectedIndex].text,10)+(12*parseInt(yearObject.options[yearObject.selectedIndex].text,10)));
		if(!isNaN(totmInt)) 
			return totmInt;
   } 
   
   return null;
}


function isSin(textObject) {
	// 02/16/99 - SCC - Will return true if textObject.value is empty (if someone clears it,
	// 				     they know it is not a sin)
	var tempStr = "";
	var tempInt = 0;
	var returnBol = false;
	var sumInt = 0;
	var sumStr = "";
	
	textObject.value = filterString(textObject.value,false,true,"");
	tempStr = textObject.value;

	if (tempStr.length == 9) {
		for (var indexInt=1;indexInt<9;indexInt++) {
			tempInt = parseInt(tempStr.charAt(indexInt-1),10);
			if ((indexInt % 2) == 0) {
				tempInt *= 2;
				if (tempInt > 9) {
					tempInt -= 9;
				}
			}
			sumInt += tempInt;
		}
		
		sumStr = ""+sumInt;
		tempInt = (10-parseInt(tempStr.charAt(tempStr.length-1),10));
		tempStr = ""+tempInt;


		if (sumStr.charAt(sumStr.length-1) == tempStr.charAt(tempStr.length-1))
			returnBol = true;
	}
	else if (tempStr.length < 1) 
		return true;

	return returnBol;

}
function do_Other(objref,optionsIdx,promptText,maxLen) {
	if (objref.selectedIndex == optionsIdx) {
		//Prompt for a value
		var otherValue = '';
		otherValue = prompt(promptText,"");
		if (otherValue == '' || otherValue == null || otherValue == 'undefined') {
			objref.options[(optionsIdx)].selected = true;
			return false;
		}
		if (otherValue.length >= maxLen)
			otherValue = otherValue.substring(0,maxLen);
		//alert('MaxLen = ' + maxLen + '\notherValue Length = '+otherValue.length+'.');			
		objref.options[(optionsIdx+1)].value = otherValue;
		objref.options[(optionsIdx+1)].text = otherValue;
		objref.options[(optionsIdx+1)].selected = true;
		return true;
	} else
		return false;
}

function validateNum(theNum,decplaces,min,max,addcommas,acceptNoneStr) {
// VALIDATE & FORMAT USER INUPT
	var str = ""+theNum.value;
	if ((str == "") || (str == "null")) {
		theNum.value = "";
		return false;
	}
	if (acceptNoneStr) {
		var str2 = stripinFun(str,".0123456789noneNONE");		// REMOVE SPACES //
		if (str2.toUpperCase() == 'NONE')
			theNum.value = "0";			// NOTICE NO RETURN; CONTINUE ON WITH REQUESTED FORMATTING //
	}
	var tmpFloat = parseFloat(filterNum(theNum.value));
	if (isNaN(tmpFloat)) {	// OTHERWISE, FIELD DISPLAYS NaN //
		theNum.value = "";
		return false;
	}
	if (tmpFloat < min || tmpFloat > max) {
		alert("Please enter a number between " + min + " and " + max + ".");
		theNum.value = "";
		theNum.focus();
		return false;
	}
	if (decplaces == 0) {
		var fmtdnum = formatInteger(theNum,decplaces);
		var checkNum = parseInt(fmtdnum,10);
	} else {
		var fmtdnum = formatRealNum(theNum,decplaces);
		var checkNum = parseFloat(fmtdnum);
	}
	if (checkNum > max)
		fmtdnum = checkNum - 1;		// This will only occur if the number has been rounded up! So round down.. //

	if (addcommas) {
		fmtdnum = commaFmt(fmtdnum);
	}
	theNum.value = fmtdnum;
	return true
}


function formatRealNum(theNum,decplaces) {
// FORMAT A REAL NUMBER TO THE DESIRED DECIMAL PLACE
	var str = Math.round(parseFloat(filterNum(theNum.value)) * Math.pow(10,decplaces));
	str = ""+str;
	while (str.length <= decplaces) {
		str = "0" + str;
	}
	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

function formatInteger(theNum) {
// FORMAT AN INTEGER
	var str = Math.round(parseFloat(filterNum(theNum.value)));
	str = ""+str;
	return str;
}

function commaFmt(numEle) {
	var tempStr = ""+numEle;
	
	// already has commas
	var charCheck = tempStr.indexOf(",");
	if ((charCheck+0) >= 0) {
		return numEle;
	}

	// separate the decimal from the whole number
	var decStr = "";
	var decInt = tempStr.indexOf(".");
	if (decInt!=-1) {
		decStr = tempStr.substring(decInt,tempStr.length);
		tempStr = tempStr.substring(0,decInt);
	}

	// if negative - save sign
	var isNeg = false;
	if (tempStr.indexOf("-")!=-1) {
		isNeg=true;
        tempStr=tempStr.substring(1,tempStr.length);
	}

	// short - no commas needed
	if (tempStr.length<=3) { 
		return numEle;
	}

	// add commas
	var newStr = "";
	var jInt = 0;
	for (var iInt=tempStr.length-1;iInt>=0;iInt--) {
		jInt++;
		newStr = tempStr.charAt(iInt) + newStr;
		if (jInt%3==0) {
			if (iInt-1>=0) {
				newStr = ","+newStr;
			}
		}
	}

	// re-assemble the parts
	if (decInt!=-1)
		newStr = newStr + decStr;
	if (isNeg)
		newStr = "-"+newStr;

	return newStr;
}

function tally(args) {
	var sumNum = 0;
	var tempNum = 0;
	var tempStr = "";
	var subBol = false;
	var doFloats = false;
	var startIndex = 0;
	if (tally.arguments[0] == "float") {
		doFloats = true;
		startIndex = 1;
	}
	
    for (var i=startIndex; i<(tally.arguments.length - 1); i++) {
		if (tally.arguments[i] == "-") {
			subBol = true;
		} else {
			tempStr = tally.arguments[i].value +"";
			tempStr = stripFun(tempStr,",");
			if (tempStr != "" && tempStr != null) {
				if (doFloats)
					tempNum = parseFloat(tempStr);
				else
					tempNum = parseInt(tempStr,10);
				if (tempNum>0) {
					if (subBol) {
						sumNum -= tempNum;
						subBol = false;
					} 
					else 
						sumNum += tempNum;
				}
			}
		}
	}
	if (doFloats && (sumNum+"").indexOf(".") == -1)
		sumNum += ".00";
	
	tally.arguments[i].value = sumNum;
}
// Function that trims whitespace from the front and back of a string
function trim(string) {
	//trim off any whitespace befor and after the string;
    var i=0;
	var returnString="";
    var whitespace = " \t\n\r";
	var just_white_space = true
	var ch = "";

	//first trim whitespaces from the front

	for (i = 0; i < string.length; i++){
		ch = string.substring(i, i+1);
        if (whitespace.indexOf(ch) == -1) {
			string=string.substring(i,string.length);
			just_white_space = false;
			break;
		}
    }
	if (just_white_space) {
		string = "";
	} else {
		//Now trim whitespaces from the back
		i=string.length
		for (i = string.length; i>=0; i--){
			ch = string.substring(i, i+1);
			if (whitespace.lastIndexOf(ch) == -1) {
				string=string.substring(0,i+1);
				break
			}
		}
	}

	return string;
}

function sizeOk(textObj,maxLength,isNum) {
	// For numeric text fields that add commas, the max size must be greater than what the db can handle (to add the commas).
	// If on ie/PC, user can fool system by entering in a bunch of numbers, then clicking on a drop down and the onChange event
	// is IGNORED, leaving the numbers occupying the comma spots AND IS THEN TOO BIG FOR THE DB.
	var workStr = ""+textObj.value;
	if (workStr=="")
		return true;
	if (isNum) {	// compare based on maximum
		var maxNum = "";
		var testNum = parseFloat(filterNum(workStr));
		if (isNaN(testNum))
			return false;
		for (var i=0;i<maxLength;i++)
			maxNum += "5";
		maxNum = parseFloat(maxNum);
		var isNeg = (testNum<0)
		testNum = Math.abs(testNum);
		//alert("maxNum for "+textObj.name+" is "+maxNum+" and testNum is "+testNum);
		if (testNum>maxNum) {
			textObj.value = (isNeg)?commaFmt("-"+maxNum):commaFmt(""+maxNum);
			return false;
		}
	}
	else {
		if (workStr.length>maxLength) {
			textObj.value = workStr.substr(0,maxLength);
			return false;
		}
	}
	return true;
}








