// ******************************************************************
// This file contains functions that are very useful for web design.
// Sadly, most of these functions were created by other people and 
// not by me.  Some have been modified to better suite my needs.
//
// The list of function in this file are as followed:
//		- ltrim (strText) 
//		- rtrim (strText)
//		- trim (strText)
//		- isdefined(variable)
//		- openPopUp(cellValue, url,target,attributes) 
//		- numbersonly(myfield, e,dec)
//		- js_formatCurrency(strValue, strDlrSign)
//		- CurrToInt(cellValue)
//		- Valid_Email(str, a)
//		- isDate(dateStr)
//		- firstFocus()
//		- FormElementIsArray(obj)
//		- CheckForDate(vThis)
//		- DefaultDate(vThis,iOn)
//		- ShowHide(vthis, varToShow)
//		- Right(str, n)
//		- Left(str, n)
//		- blockSubmitButton(a,newButtonName,alertMsg)
//		- dateAdd(start, interval, number)
//		- highlightTextField(field)
//		- UnHighlightTextField(field)
//		- highlightSelectField(field)
//		- Format_Float(vThis,iDecPlaces)
//		- StrToDate(strDate)
//   		- EmployeeNumberOnly(myfield, e)
//		- ToggleHidden (fieldID)
//		- letternumber(e,blnAllowSpaces)
//		- randomString(e,intSize)
// ******************************************************************
//------------------------------------------------------------------------------------------
function ltrim(strText) { 
    // this will get rid of leading spaces 
    while (strText.charCodeAt(0) == 160 || strText.charCodeAt(0) == 32)
		strText = strText.substring(1, strText.length)
	return strText;
}
//------------------------------------------------------------------------------------------
function rtrim(strText){
    // this will get rid of trailing spaces 
    while (strText.charCodeAt(strText.length-1) == 160  || strText.charCodeAt(strText.length-1) == 32) 
        strText = strText.substring(0, strText.length-1);        
   return strText;
}
//------------------------------------------------------------------------------------------
function trim(strText) { 
    // this will get rid of leading/trailing spaces 
   return ltrim(rtrim(strText));
}
//------------------------------------------------------------------------------------------
// isdefined:  used to verify that a varible has been defined in case 
//             variables are created dynamically
function isdefined(a) { 
	return (typeof(window[a]) == "undefined")? false: true; 
	//return (typeof(variable) == "undefined")? false: true; 
} 
//----------------------------------------------------------------------------------------
function isObject(a) {
    return (a && typeof a == 'object')
}
//----------------------------------------------------------------------------------------
function isUndefined(a) {
    return typeof a == 'undefined';
}
//----------------------------------------------------------------------------------------
function openPopUp(url,target,attributes,popup_size) {
// THIS SCRIPT FROM BRAVENET
	var def_attributes = 'channelmode=no;directories=no;toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=no,';
	//var def_attributes = 'channelmode=no,directories=yes,toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,';
	if (attributes == '') attributes = def_attributes;
	attributes += popup_size;
	popup = window.open(url,target,attributes);
	//popup.moveTo((window.screen.availWidth -  550) / 2, (window.screen.availHeight - 700) / 2);
	popup.moveTo(100,50);
	popup.focus();blur();
}
//----------------------------------------------------------------------------------------
// numbersonly: When you want to limit numeric values only in any textbox. 
// How to Use: <input type="textbox" ... onKeyPress="return numbersonly(this, event)" >
function numbersonly(myfield, e,dec){
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);

	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789.-/").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == ".")){
	   myfield.form.elements[dec].focus();
	   return false;
	}
	else
	   return false;
}
//----------------------------------------------------------------------------------------
// js_formatCurrency: formats a string into currency format
function js_formatCurrency(strValue, strDlrSign){
	strValue = strValue.toString().replace(/\$[\s]|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue * 100 + 0.50000000001);
	intCents = dblValue % 100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if (intCents < 10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + strDlrSign + dblValue + '.' + strCents);
}
//----------------------------------------------------------------------------------------
//  CurrToInt: Formats any currency value to a numeric value (i.e. Strips currency and commas)
function CurrToInt(cellValue){
	return cellValue.replace(/\$[\s]|\,/g,'') * 1;
}
//----------------------------------------------------------------------------------------
function Valid_Email(strEmailList, a) {
	var at="@";
	var dot=".";
	var del=",";
	var strEmail="";
	var lat="";
	var lstr="";
	var ldot="";
	var msg="";
	
	strEmailList = strEmailList.replace(/;/g,',');
	var ldel=strEmailList.indexOf(del);
	var temp = new Array();
	temp = strEmailList.split(del);
	if (strEmailList.length == 0) return true;
	for (i=0;i<temp.length;i++){
		strEmail = trim(temp[i]);
		msg = 'Invalid E-mail (' + strEmail + ') address detected in the "' + a + '" field.\n\nPress ESC twice to clear the field.';
		lat=strEmail.indexOf(at);
		lstr=strEmail.length;
		ldot=strEmail.indexOf(dot);
		if (lat == -1){
		   alert(msg);
		   return false;
		}
	
		if (lat==-1 || lat==0 || lat==lstr){
		   alert(msg);
		   return false;
		}
	
		if (ldot==-1 || ldot==0 || ldot==lstr){
		    alert(msg);
		    return false;
		}
	
		 if (strEmail.indexOf(at,(lat+1))!=-1){
		    alert(msg);
		    return false;
		 }
	
		 if (strEmail.substring(lat-1,lat)==dot || strEmail.substring(lat+1,lat+2)==dot){
		    alert(msg);
		    return false;
		 }
	
		 if (strEmail.indexOf(dot,(lat+2))==-1){
		    alert(msg);
		    return false;
		 }
		
		 if (strEmail.indexOf(" ")!=-1){
		    alert(msg);
		    return false;
		 }
	}
	return true;
}
//------------------------------------------------------------------------------------------
function isDate(dateStr) {
// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?

    if (matchArray == null) {
        //alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
        return false;
    }

    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[5];

    if (month < 1 || month > 12) { // check month range
        //alert("Month must be between 1 and 12.");
        return false;
    }

    if (day < 1 || day > 31) {
        //alert("Day must be between 1 and 31.");
        return false;
    }

    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
        //alert("Month "+month+" doesn't have 31 days!")
        return false;
    }

    if (month == 2) { // check for february 29th
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            //alert("February " + year + " doesn't have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}
//------------------------------------------------------------------------------------------
// setData: this works with a checkbox and a textbox used for a date value.
//          when vThis is checked, it then sets dateField's value to today's date.
//	    note: backDate can be used to set the date back/ahead 'x' number of days
//		  by setting the '0' to a negative/positive number
function SetDate (vThis, dateField){
	var y = document.frmMain;
	if (vThis.checked) {
		document.getElementById(dateField).disabled = false;
		var today=new Date();
		var backDate = dateAdd (today, 'd', '0');
		if (typeof (y.Inspection_dt) == 'undefined')
			today = backDate;
		else
			today = new Date(y.Inspection_dt.value);
		document.getElementById(dateField).value = (today.getMonth()+1)+"/"+(today.getDate())+"/"+today.getYear();
		document.getElementById(dateField).select();
		document.getElementById(dateField).focus();
	}
	else {
		document.getElementById(dateField).value = '';
		document.getElementById(dateField).disabled = true;
	}
}
//------------------------------------------------------------------------------------------
// Base Code from http://javascript.about.com/library/scripts/blfirstfocus.htm
// firstFocus: sets focus to the first available form element.
//	       frmMain is my default form name and takes precedence over the any other form
function firstFocus(){
	if (document.forms.length > 0){
		if (isdefined('frmMain')) {
	  		var TForm = document.frmMain;
		}
		else {
			var TForm = document.forms[0];
		}
		for (i=0;i<TForm.length;i++){
			if (document.getElementById(TForm.elements[i].id).disabled==false) {
				if ((TForm.elements[i].type=="text") || (TForm.elements[i].type=="textarea") || 
					(TForm.elements[i].type=="file") || (TForm.elements[i].type=="radio") || 
					(TForm.elements[i].type=="button") || (TForm.elements[i].type.toString().charAt(0)=="s")) {
				document.getElementById(TForm.elements[i].id).focus();
				break;
				}
			}
      	}
   	}
}
//------------------------------------------------------------------------------------------
function FormElementIsArray(obj){
	var e = document.getElementsByName(obj);
	if (e.length > 1)			//Is an array
		return true;
	else if (e.length == 1)		//Is Not array
		return false;
	else {
		alert (obj + " is not a valid object!  Check your code.");
		return false;
	}
}
//------------------------------------------------------------------------------------------
function CheckForDate(vThis){
	if (!isDate(vThis)) {
		alert('Not a valid date or \nin an acceptable format [mm/dd/yyyy]!!!\n\nHit [esc] to return previous date.');
		return false;
	}
	else{
		return true;
	}
}
//------------------------------------------------------------------------------------------
// DefaultDate: Used to set default values to texboxes used for dates.
//	iOn is used to flag the function when to check for the value
//	iOn = 0: Checks the value when you leave the textbox (loose focus)
//	iOn = 1: Checks the value on Focus
function DefaultDate(vThis,iOn){
	if (iOn == '0') {			//onBlur
		if (vThis.value =='') vThis.value = '[mm/dd/yyyy]';
	}
	else if (iOn == '1') {		//onFocus
		if (vThis.value=='[mm/dd/yyyy]') vThis.value='';
	}
}
//----------------------------------------------------------------------------------------
// SHowHide: used to display/hide large blocks of HTML code.  I used it to display
//	additional code based on data input, mainily radio buttons Yes/No
// vthis needs to be passed 'this' in the call
// varToShow is the value of the ID attribute of the SPAN tag to show and hide
function ShowHide(vthis, varToShow){
	var y = document.getElementById(varToShow);
	if (vthis.value == 'Yes')
		y.innerHTML = eval(varToShow)
	else 
		y.innerHTML = '';
}
//----------------------------------------------------------------------------------------
function Left(str, n){
//    Scott Mitchell - mitchell@4guysfromrolla.com
//    http://www.4GuysFromRolla.com
/***
	IN: str - the string we are LEFTing
	    n - the number of characters we want to return
	
	RETVAL: n characters from the left side of the string
***/
	if (n <= 0)     // Invalid bound, return blank string
    	return "";
	else if (n > String(str).length)   // Invalid bound, return
		return str;                // entire string
	else // Valid bound, return appropriate substring
		return String(str).substring(0,n);
}
//----------------------------------------------------------------------------------------
function Right(str, n){
//    Scott Mitchell - mitchell@4guysfromrolla.com
//    http://www.4GuysFromRolla.com
/***
	IN: str - the string we are RIGHTing
	   n - the number of characters we want to return
	
	RETVAL: n characters from the right side of the string
***/
	if (n <= 0)     // Invalid bound, return blank string
	   return "";
	else if (n > String(str).length)   // Invalid bound, return
	   return str;                     // entire string
	else { // Valid bound, return appropriate substring
	   var iLen = String(str).length;
	   return String(str).substring(iLen, iLen - n);
	}
}
//----------------------------------------------------------------------------------------
function blockSubmitButton(a,newButtonName,alertMsg){
	if (a.value != newButtonName) {
		a.value = newButtonName;
		return true;
	} else
	{
		alert(alertMsg);
		return false;
	}
}
//----------------------------------------------------------------------------------------
// EXTRA CODE FROM A PREVIOUS PROJECT OF MINE
function fillBreakdown(){
	var sSel='';
	var ndx=0;
	// Deletes the dropdown contents
	for (i = document.frmMain_PO.selBreakDown.options.length - 1; i >= 0; i--) document.frmMain_PO.selBreakDown.options[i] = null;
	document.frmMain_PO.selBreakDown.selectedIndex = 0;
	
	// Populate the Select box
	if (document.frmMain_PO.chkAmtType.checked) {
		for (i=0; i < js_aryLabor[1].length; i++) {
			document.frmMain_PO.selBreakDown.options[i] = new Option(js_aryLabor[1][i],js_aryLabor[0][i]);
			if (sSel==js_aryLabor[0][i]) ndx = i;
		}
	}
	else {
		//alert(js_aryMaterial[1].length);
		for (j=0; j < js_aryMaterial[1].length; j++) {
			document.frmMain_PO.selBreakDown.options[j] = new Option(js_aryMaterial[1][j],js_aryMaterial[0][j]);
			if (sSel==js_aryMaterial[0][j]) ndx = j;
		}
	}
	document.frmMain_PO.selBreakDown.selectedIndex = ndx;
}
//----------------------------------------------------------------------------------------
// dateAdd: used in setDate function to add intervals to a valid date.
function dateAdd(start, interval, number) {
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n"
        startMsg += "must be a valid date format.\n\n"
        startMsg += "Please try again." ;
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n"
        intervalMsg += "d, h, m OR s intervals.\n\n"
        intervalMsg += "Please try again." ;

    var numberMsg = "Sorry the number parameter of the dateAdd function\n"
        numberMsg += "must be numeric.\n\n"
        numberMsg += "Please try again." ;
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start ) ;
	
    // check that the start parameter is a valid Date. 
    if ( isNaN (buffer) ) {
        alert( startMsg ) ;
        return null ;
    }
	
    // check that an interval parameter was not numeric. 
    if ( interval.charAt == 'undefined' ) {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg ) ;
        return null ;
    }

    // check that the number parameter is numeric. 
    if ( isNaN ( number ) )	{
        alert( numberMsg ) ;
        return null ;
    }

    // so far, so good...
    //
    // what kind of add to do? 
    switch (interval.charAt(0))
    {
        case 'd': case 'D': 
            number *= 24 ; // days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60 ; // hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60 ; // minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000 ; // seconds to milliseconds
            break ;
        default:
        // If we get to here then the interval parameter didn't
        // meet the d,h,m,s criteria.  Handle the error. 		
        alert(intervalMsg) ;
        return null ;
    }
    return new Date( buffer + number ) ;
}
//----------------------------------------------------------------------------------------
// This outlines an input field in red for required data
function highlightTextField(field) {
	field.style.borderColor = '#ff0000';
	field.style.borderStyle = 'solid';
	field.style.borderWidth = '2px;';
}
//----------------------------------------------------------------------------------------
// This returns outlines of an input field to the default color for required data
function UnHighlightTextField(field,defColor) {
	field.style.borderColor = defColor;
	field.style.borderStyle = 'solid';
	if (defColor > '') field.style.borderWidth = '1px;';
	else field.style.borderWidth = '0px;';
}
//----------------------------------------------------------------------------------------
// This outlines a Dropdown field in red for required data
function highlightSelectField(field) {
	field.style.backgroundColor = 'red';
	field.style.color = 'white';
}
//----------------------------------------------------------------------------------------
// This formats a number to a float to iDecPlaces 
function Format_Float(vThis,iDecPlaces){
	var strThis = vThis.value.toString().replace(/\$[\s]|\,/g,'');
	var dblValue = parseFloat(strThis);
	var blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	var lngPower = Math.pow(10,iDecPlaces);
	var dblValue = Math.floor(dblValue * lngPower + 0.50000000001);
	var intCents = dblValue % lngPower;
	var strCents = intCents.toString();
	dblValue = Math.floor(dblValue/lngPower).toString();
	while (strCents.length < (String(lngPower).length-1)) {
	//if (intCents < 1000)
		strCents = "0" + strCents;
	}
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+dblValue.substring(dblValue.length-(4*i+3));
	//return ((blnSign)?'':'-') +  dblValue + '.' + strCents;
	vThis.value = ((blnSign)?'':'-') +  dblValue + '.' + strCents;
}
//----------------------------------------------------------------------------------------
// This formats a string to a Date for comparisons.
function StrToDate(strDate){
	if (strDate == '') 
		var d1 = new Date();
	else 
		d1 = new Date(strDate);
	return d1;
}
//----------------------------------------------------------------------------------------
// EmployeeNumberOnly: When you want to limit to pnly 5 digit numeric values or T values with 5 digits in any textbox. 
// How to Use: <input type="textbox" ... onKeyPress="return EmployeeNumberOnly(this, event)" >
function EmployeeNumberOnly(myfield, e){
	var key;
	var keychar;

	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) ||
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	else if ((myfield.value.length == 5) && (myfield.value.substr(0,1) != 'T'))
		return false;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
		 
	else if ((keychar == 'T') && (myfield.value == ''))
		 return true;
		 
	else
	   return false;
}
//----------------------------------------------------------------------------------------
// ToggleHidden: Flips elements to displayed or not.
// How to use: <a href="javascript:ToggleHidden('ElementID')">test</a> works rather well
function ToggleHidden(a) {
	if (document.getElementById(a).style.display == '') 
		document.getElementById(a).style.display = 'none';
	else
		document.getElementById(a).style.display = '';
}
//----------------------------------------------------------------------------------------
// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function letternumber(e,blnAllowSpaces){
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	keychar = keychar.toLowerCase();
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) ||
		(blnAllowSpaces && key==32) )
	   return true;
	// alphas and numbers
	else if ((("abcdefghijklmnopqrstuvwxyz0123456789").indexOf(keychar) > -1))
	   return true;
	else {
		alert('Letters and Numbers Only.');
		return false;
	}
}
//----------------------------------------------------------------------------------------
// Copied from http://www.mediacollege.com/internet/javascript/number/random.html
// e = the field ID where to put the results.
// intSize = the number of characgers for the results
function randomString(e,intSize) {
	var chars = '123456789ABCDEFGHIJKLMNPQRSTUVWXTZ';
	intSize = parseInt(intSize);
	if (isNaN(intSize) || (intSize < 1) || (intSize > 99)) {intSize = 8;}
	var string_length = intSize;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	document.getElementById(e).value = randomstring;
}
