﻿//<SCRIPT>
//// EntryControl.js ////

if(typeof(SBNet) == "undefined")
{
	SBNet={};
}

SBNet.EC = {

//// Numeric controls /////////////////////////////////////////////

IntegerEntry:function(oControl, bInitFormat, bPositiveOnly, min, max)
{
	//Setup format type.
	oControl.FormatControl = this.formatInteger;
	//Set my entry characters.
	if((bPositiveOnly != null) && (bPositiveOnly == true))
		oControl.EntryKeyList = "0123456789";
	else
		oControl.EntryKeyList = "0123456789-";
	this.setMinMax(oControl, min, max, parseInt);
	this.EntryControl(oControl, bInitFormat);
},

formatInteger:function(strInput)
{
	strInput = SBNet.EC.entryTrimLeft(strInput, "0");
	if(strInput.length == 0)
		strInput = "0";
	strInput = SBNet.EC.formatFloat(strInput);
	if(strInput == null)
		return null;
	var iAmount = parseInt(strInput);
	if (isNaN(iAmount))
		return null;
	//if(iAmount == 0)
	//	return "";
	return iAmount.toString(10);
},

FloatEntry:function(oControl, bInitFormat, bPositiveOnly)
{
	//Setup format type.
	oControl.FormatControl = this.formatFloat;	
	//Set my entry characters.
	if((bPositiveOnly != null) && (bPositiveOnly == true))
		oControl.EntryKeyList = "0123456789.";
	else
		oControl.EntryKeyList = "0123456789-.";

	this.EntryControl(oControl, bInitFormat);
},

formatFloat:function(strInput)
{
	if(strInput.length == 0)
		strInput = "0";
	var fAmount = parseFloat(strInput);
	if (isNaN(fAmount))
		return null;

	//Can round like this...
	//fAvg.toFixed(3)
    
    // Convert to a String
	return fAmount.toString(10);
},

USCurrencyEntry:function(oControl, bInitFormat, bPositiveOnly, min, max)
{
	//Setup format type.
	oControl.FormatControl = this.formatUSCurrency;	
	//Set my entry characters.
	if((bPositiveOnly != null) && (bPositiveOnly == true))
		oControl.EntryKeyList = "0123456789.";
	else
		oControl.EntryKeyList = "0123456789-.";
	this.setMinMax(oControl, min, max, parseFloat);
	this.EntryControl(oControl, bInitFormat);
},

formatUSCurrency:function(strInput)
{
	if(strInput.length == 0)
		strInput = "0";

	var fAmount = parseFloat(strInput.replace(/,|^\$/g, ""));  // Strip money symbols 
	if (isNaN(fAmount))
		return null;

	//Can round like this...
	return fAmount.toFixed(2);
},

NumericEntry:function(oControl, bInitFormat)
{
	//Setup regular expression.
	oControl.RegExpMatch = /^[\d]*$/m;
	oControl.RegExpReplace = /[^\d]*/mg;

	this.EntryControl(oControl, bInitFormat);
},

USPhoneEntry:function(oControl, bInitFormat)
{
	//Setup format type.
	oControl.FormatControl = this.formatUSPhone;	
	//Set my entry characters.
	oControl.EntryKeyList = "0123456789.()-";
	this.EntryControl(oControl, bInitFormat);
},

formatUSPhone:function(strInput)
{
	if(strInput.length == 0)
		return "";

	var s = strInput.replace(/[^\d]*/mg, "");  // Strip non-digits 
	s = SBNet.EC.entryTrim(s);
	if(s.length == 10)
		return s.substr(0, 3) + "-" + s.substr(3, 3) + "-" + s.substr(6, 4);
	else
	if(s.length == 11)
		return s.substr(0, 1) + "-" + s.substr(1, 3) + "-" + s.substr(4, 3) + "-" + s.substr(7, 4);
	return null;
},

EmailEntry:function(oControl, bInitFormat)
{
	//Setup format type.
	oControl.FormatControl = this.formatEmail;	
	this.EntryControl(oControl, bInitFormat)
},

formatEmail:function(strInput)
{
	if(strInput.length == 0)
		return "";

	var s = strInput.match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
	if(s == null)
		return null;
	return strInput;
},

//// Text controls /////////////////////////////////////////////

SafeTextEntry:function(oControl, bInitFormat)
{
	// [^\w\s'".,~`!@#$%\&\*\(\)\-\+=\{\}\[\]:;\?\\/\\|]*
	// 
	// Matches about all characters execpt these «<>^»
	//    The «<>^» characters cause problems with ASP.NET post backs.
	oControl.RegExpMatch = /^(?:[\w\s'".,~`!@#$%\&\*\(\)\-\+=\{\}\[\]:;\?\\\/|]*)$/m;
	oControl.RegExpReplace = /[^\w\s'".,~`!@#$%\&\*\(\)\-\+=\{\}\[\]:;\?\\\/|]*/mg;
	oControl.FormatControl = this.entryTrim;	

	this.EntryControl(oControl, bInitFormat)
},

SqlSafeTextEntry:function(oControl, bInitFormat)
{
	// [^\w '"]*
	// 
	// Match a single character NOT present in the list below «[^\w '"]*»
	//    Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
	//    Match a single character that is a "word character" (letters, digits, etc.) «\w»
	//    One of the characters " '"" « '"»
	oControl.RegExpMatch = /^(?:[\w '"]*)$/m;
	oControl.RegExpReplace =/[^\w '"]*/mg;
	oControl.FormatControl = this.entryTrim;	

	this.EntryControl(oControl, bInitFormat);
},

SafeFileNameTextEntry: function(oControl, bInitFormat) 
{
        // Matches about all characters execpt these «<>^»
        //    The «<>^» characters cause problems with ASP.NET post backs.
        oControl.RegExpMatch = /^(?:[\w ~!@#$%()_\-\/'"]*)$/m;
        oControl.RegExpReplace = /[^\w '"]*/mg;
        oControl.FormatControl = this.entryTrim;

        this.EntryControl(oControl, bInitFormat);
},


UpperCaseTextEntry:function(oControl, bInitFormat)
{
	oControl.UpperCaseOnly = true;
	//Setup format type.
	oControl.FormatControl = this.formatUpperCase;	

	this.EntryControl(oControl, bInitFormat);
},

formatUpperCase:function(strInput)
{
	return strInput.toUpperCase();
},

PasswordEntry:function(oControl, bInitFormat)
{
	//Setup regular expression.
	oControl.RegExpTest = /^[\d\w_-]{4,12}$/;

	this.EntryControl(oControl, bInitFormat);
},

//// Date control /////////////////////////////////////////////

DateEntry:function(oControl, bInitFormat)
{
	//Set my entry characters.
	oControl.EntryKeyList = "0123456789-./";
	//Setup format type.
	oControl.FormatControl = this.formatDate;	

	this.EntryControl(oControl, bInitFormat);
},

// Will parse date by '.', '-', and '/'. Using these
// formats:MM-DD-YYYY, MM-DD-YY, YYYY-MM-DD, MMDDYYYY, MMDDYY, MMDD.
// Returns: MM/DD/YYY
formatDate:function(strInput)
{
	//Empty string OK?
	if(strInput.length == 0) return '';

	var iMonth, iDay, iYear;
	var sMonth, sDay, sYear;
	var date = new Date();
	var sCurYear = date.getFullYear().toString();
	var parts;

	//Parse the string by '.', '-', and '/'.
	//parts = strInput.split(/^[\.\/-]$/g);
	parts = strInput.split(/[\.\/-]/);

	if(parts.length == 3) // MM-DD-YY
	{
		if(parts[0].length == 4) //Year first.
		{
			sMonth = parts[1];
			sDay = parts[2];
			sYear = parts[0];
		}
		else  //Month first.
		{
			sMonth = parts[0];
			sDay = parts[1];
			sYear = parts[2];
		}
	}
	else
	if(parts.length == 2)  // MM-DD
	{
		sMonth = parts[0];
		sDay = parts[1];
		sYear = sCurYear;
	}
	else
	if(parts.length == 1)  //MMDDYY or MMDDYYYY
	{
		if(parts[0].length >= 4)
		{
			sMonth = parts[0].substr(0, 2);
			sDay = parts[0].substr(2, 2);
			if(parts[0].length >= 6)
				sYear = parts[0].substr(4);
			else
				sYear = sCurYear;
		}
		else   //Don't know...
			return null;	
	}
	else   //Don't know...
		return null;	

	 //// verify month  ////
	//Change it to a number and check it.
	iMonth = parseInt(sMonth, 10);
	if(iMonth > 12 || iMonth < 1)
		return null;
	//Make it 2 digits.
	sMonth = (iMonth < 10) ? "0" : "";	
	sMonth += iMonth.toString(10);	
	
  //// verify day  ////
	//Change it to a number and check it.
	iDay = parseInt(sDay, 10);
	if(iDay > 31 || iDay < 1)
		return null;
	//Make it 2 digits.
	sDay = (iDay < 10)? "0" : "";	
	sDay += iDay.toString(10);	

  //// verify year  ////
	//Change it to a number and check it.
	iYear = parseInt(sYear, 10);
	//Make sure it is a real year.
	if((iYear > (date.getFullYear() + 1000)) || (iYear < 0))
		return null;
	if(iYear < 1000)
	{
		if(iYear > 99)
			return null;

		var iCurHun = parseInt(sCurYear.substr(0, 2), 10);
		var iCurTen = parseInt(sCurYear.substr(2), 10);
		var iTen = parseInt(sYear, 10);
		//if the year difference is more than 30, go back
		// one hundred years.
		if(Math.abs(iCurTen - iTen) > 30)
			sYear = ((iCurHun - 1) * 100 + iYear).toString();
		else
			sYear = (iCurHun * 100 + iYear).toString();
		iYear = parseInt(sYear, 10);
	}

	//Validate.
	if(SBNet.EC.isValidDatePieces(iMonth, iDay, iYear) == false)
		return null;
		
	//Add the "/"'s in.
	return (sMonth + "/" + sDay + "/" + sYear);	
},

isValidDatePieces:function(iMonth, iDay, iYear)
{
	//NOTE: These are 1 based values.
	if((iMonth == 1) || (iMonth == 3) || (iMonth == 5) || (iMonth == 7) ||
		 (iMonth == 8) || (iMonth == 10) || (iMonth == 12))
	{
		if((iDay >= 1) && (iDay <= 31))
			return true;
	}
	else 
	if((iMonth == 4) || (iMonth == 6) || (iMonth == 9) || (iMonth == 11))
	{
		if((iDay >= 1) && (iDay <= 30))
			return true;
	}
	else
	if(iMonth == 2) //Should be February.
	{
		//We know the year, we could calculate leap year?
		if((iDay >= 1) && (iDay <= 29))
			return true;
	}
	return false;
},	

//// Zipcode control /////////////////////////////////////////////

ZipEntry:function(oControl, bInitFormat)
{
	//Set my entry characters.
	oControl.EntryKeyList = "0123456789-";
	//Setup format type.
	oControl.FormatControl = this.formatZip;	

	this.EntryControl(oControl, bInitFormat);
},

//
// Formats zip as '12345' or '12345-1234'.
//
formatZip:function(strInput)
{
	if (strInput.length == 0) return '';
		var str = strInput.replace(/[^\d]*/mg, "");  // Strip non-digits 
	//Should be 5 or 9 digits.
	if((str.length != 5) && (str.length != 9))
		return null;

	//Add the "-" back in.
	if(str.length == 5)
		return str;
	else
		return (str.substr(0,5) + "-" + str.substr(5,4));	
},

//// Time control /////////////////////////////////////////////

TimeEntry:function(oControl, bInitFormat)
{
	//Set my entry characters.
	oControl.EntryKeyList = "0123456789.:";
	//Setup format type.
	oControl.FormatControl = this.formatTime;	

	this.EntryControl(oControl, bInitFormat);
},

//
// Will parse time by '.' and ':'. Using these
// formats: HH:MM:SS, HH:MM, HHMMSS, HHMM, HH, H.
//
formatTime:function(strInput)
{
	//Empty string OK?
	if(strInput.length == 0) return '';

	var iHours, iMins, iSecs;
	var sHours, sMins, sSecs;
	var parts;

	//Parse the string by '.' and ':'.
	parts = strInput.split(/[\.:]/);

	if(parts.length == 3)
	{
		sHours = parts[0];
		sMins = parts[1];
		sSecs = parts[2];
	}
	else
	if(parts.length == 2)
	{
		sHours = parts[0];
		sMins = parts[1];
		sSecs = "00";
	}
	else
	if(parts.length == 1)
	{
		if(parts[0].length == 6)
		{
			sHours = parts[0].substr(0, 2);
			sMins = parts[0].substr(2, 2);
			sSecs = parts[0].substr(4);
		}
		else
		if(parts[0].length == 4)
		{
			sHours = parts[0].substr(0, 2);
			sMins = parts[0].substr(2);
			sSecs = "00";
		}
		else
		//if(parts[0].length == 2) //Do same for length == 1.
		{
			sHours = parts[0];
			sMins = sSecs = "00";
		}
		//else
		//	return null;	
	}
	else
		return null;	

	//// Verify hours ////
	iHours = parseInt(sHours, 10);
	if((iHours > 23) || (iHours < 0))
		return null;
	sHours = (iHours < 10) ? "0" : "";	
	sHours += iHours.toString(10);	
		
	//// Verify minutes ////
	iMins = parseInt(sMins, 10);
	if((iMins > 59) || (iMins < 0))
		return null;
	sMins = (iMins < 10) ? "0" : "";	
	sMins += iMins.toString(10);	

	//// Verify seconds ////
	iSecs = parseInt(sSecs, 10);
	if((iSecs > 59) || (iSecs < 0))
		return null;
	sSecs = (iSecs < 10) ? "0" : "";	
	sSecs += iSecs.toString(10);	

	return (sHours + ":" + sMins + ":" + sSecs);	
},

//// Common control functions /////////////////////////////////////////////

//Trim 'sChar' characters from the left and right
// of 'sText'. 'sChar' defaults to space.
entryTrim:function(sText, sChar)
{
	return SBNet.EC.entryTrimRight(SBNet.EC.entryTrimLeft(sText, sChar), sChar);
},

//Trim 'sChar' characters from the left of 'sText'.
// 'sChar' defaults to a space.
entryTrimLeft:function(sText, sChar)
{
	if(sChar == null)
		sChar = " ";
		
	for(var i = 0; i < sText.length; i++)
	{
		if(sText.charAt(i) != sChar)
			break;
	}
	return sText.substr(i);	
},

//Trim 'sChar' characters from the right of 'sText'.
// 'sChar' defaults to a space.
entryTrimRight:function(sText, sChar)
{
	if(sChar == null)
		sChar = " ";
		
	for(var i = (sText.length - 1); i >= 0; i--)
	{
		if(sText.charAt(i) != sChar)
			break;
	}
	return sText.substr(0, i + 1);
	return sText;
},

EntryFormatsAreValid:function() 
{
	var aControlList = new Array();
    var aInputList = document.body.getElementsByTagName("INPUT");
    var aTextArea = document.body.getElementsByTagName("TEXTAREA");
    var i;
    
    for(i = 0; i < aInputList.length; i++)
        aControlList.push(aInputList[i]);
    for(i = 0; i < aTextArea.length; i++)
        aControlList.push(aTextArea[i]);


	//I had this restriction for some reason??? I can't remember now... -sc 10/30/2007
	//if(SBNet.EC.isIE == true)
	{
		for(i = 0; i < aControlList.length; i++)
			SBNet.EC.TestControl(aControlList[i]);
	}
	for(i = 0; i < aControlList.length; i++)
	{
		if((aControlList[i].ValidFormat != null) && (aControlList[i].ValidFormat == false))
			return false;
	}
	return true;
},

ResetInvalidFields:function() 
{
	var aControlList = new Array();
    var aInputList = document.body.getElementsByTagName("INPUT");
    var aTextArea = document.body.getElementsByTagName("TEXTAREA");
    var i;
    
    for(i = 0; i < aInputList.length; i++)
        aControlList.push(aInputList[i]);
    for(i = 0; i < aTextArea.length; i++)
        aControlList.push(aTextArea[i]);

	for(i = 0; i < aControlList.length; i++)
	{
		if(aControlList[i].BKColor != aControlList[i].style.backgroundColor)
		{
			aControlList[i].style.backgroundColor = aControlList[i].BKColor;
			aControlList[i].ValidFormat = true;
		}
	}
},

EntryControl:function(oControl, bInitFormat)
{
	//Setup event handlers.
	oControl.onkeypress = SBNet.EC.OnEntryKeyPress;	
	oControl.onblur = SBNet.EC.OnEntryBlur;
	//Remember the current background color.
	oControl.BKColor = oControl.style.backgroundColor;	
	oControl.ValidFormat = true;		
	if((bInitFormat != null) && (bInitFormat == true))
	{
		//SBNet.EC.entryFormatControl(oControl);
		SBNet.EC.TestControl(oControl);
	}
},

setMinMax:function(oControl, min, max, parseWith)
{
	if(min != null)
		oControl.MinValue = parseWith(min);	
	if(max != null)
		oControl.MaxValue = parseWith(max);	
	oControl.parseWith = parseWith;
},

AllowNoValue:function(oControl, bOption)
{
	if(bOption != null)
		oControl.AllowNoValue = bOption;	
	else
		oControl.AllowNoValue = true;	
},

IsRequired:function(oControl, bOption)
{
	if(bOption != null)
		oControl.IsRequired = bOption;	
	else
		oControl.IsRequired = true;	
},

SetMinLength:function(oControl, nLength)
{
	oControl.MinLength = nLength;	
},

GetFormatedValue:function(oControl)
{
	if(oControl.FormatControl != null)
		return oControl.FormatControl(oControl.value);
	return oControl.value;
},

entryFormatControl:function(oControl)
{
	var val = SBNet.EC.GetFormatedValue(oControl);
	if(val != null)
		oControl.value = val;
},

OnEntryKeyPress:function(keyEvent)
{
	var key = SBNet.EC.GetKeyCode(keyEvent);
	if(key == null)
	{
		alert("ERROR: OnEntryKeyPress can not determine key code!");
		return true;
	}
	
	//alert("key = " + key + " (" + String.fromCharCode(key) + ")");
	//return true;

	var oControl = this;
	//alert(oControl);
   //Remember last key.
   oControl._lastKey = key;
   
	if(oControl.BKColor != oControl.style.backgroundColor)
		oControl.style.backgroundColor = oControl.BKColor;	

	 //Handle control keys.
	 //Enter = 13, Esc = 27, Tab = 9, Backspace = 8,
	 // Shift = 16, Ctrl = 17
	 if((key == null) || (key == 0) || (key == 8) ||
		(key == 9) || (key == 13) || (key == 27) ||
		(key == 16) || (key == 17))
		return true;

	var sKeyCode = String.fromCharCode(key);
	//alert(sKeyCode);

	if(((oControl.EntryKeyList != null) &&
		(oControl.EntryKeyList.indexOf(sKeyCode) == -1)) ||
		((oControl.EntryNotKeyList != null) &&
		(oControl.EntryNotKeyList.indexOf(sKeyCode) != -1)) ||
		((oControl.RegExpMatch != null) &&
		(sKeyCode.match(oControl.RegExpMatch) == null)))
	{
		if(window.event)
			event.cancelBubble = true;
		else
			keyEvent.returnvalue = false;
		return false;
	}
	
	//This seem not work with IE7 but earlier IE's?
	/*
	if(oControl.UpperCaseOnly != null)
	{
		if((key >= 97) && (key <= 122))
		{
			if(SBNet.EC.isIE)
			{
				//alert("at UpperCaseOnly: keyEvent.keyCode -= 32");
				keyEvent.keyCode -= 32;
			}
			else
			{
				//NOTE: This don't work for NS.
				//keyEvent.which -= 32;
				//The UpperCase control will be formatted
				// in the "onblur" event.
			}
		}
	}
	*/
	return true;
},

GetKeyCode:function(keyEvent)
{
	var key;

	//alert("(A) typeof(keyEvent) = " + typeof(keyEvent));
	if(typeof(keyEvent) != "undefined" && typeof(keyEvent.which) != "undefined")
	{
		//Most non IE browsers fall in here.
		//alert("(B) keyEvent.which = " + keyEvent.which);
		key = keyEvent.which;
	}
	else
	if(typeof(event) != "undefined")
	{
		if(typeof(event.which) != "undefined")
		{
			if(event.which != 0)
			{
				//alert("(C) event.which = " + event.which);
				key = event.which;
			}
			else
			{
				//alert("(D) event.keyCode = " + event.keyCode);
				key = event.keyCode;
			}
		}
		else
		{
			//alert("(E) event.keyCode = " + event.keyCode);
			key = event.keyCode;
		}
	}
	else
	if(typeof(window.event) != "undefined")
	{
		//alert("(F) window.event.keyCode = " + window.event.keyCode);
		key = window.event.keyCode;
	}
	else
	{
		alert("ERROR: OnEntryKeyPress can not determine key code!");
		return null;
	}
	return key;
},

OnEntryBlur:function()
{
	var oControl = this;
	SBNet.EC.TestControl(oControl);
},

TestControl:function(oControl)
{
	var s = null;
	//alert(oControl);
	    
	if((oControl.FormatControl != null) || (oControl.RegExpReplace != null))
	{
		//Apply the format if supplied.
		if(oControl.FormatControl != null)
			s = oControl.FormatControl(oControl.value);

		//Test the regular expression if supplied.
		if(oControl.RegExpReplace != null)
		{
			if(s == null)
				s = oControl.value;
			//if((s.length > 0) && (s.match(oControl.RegExpReplace) == null))
			//	s = null;
			if(s.length > 0)
				 s = s.replace(oControl.RegExpReplace, "");
		}

		var doMinMax = true;
		if((s != null) && (oControl.AllowNoValue != null) && (oControl.AllowNoValue == true))
		{
			if(oControl.parseWith(s) == 0)
			{
				s = "";
				doMinMax = false;
			}
		}
		if(doMinMax)
		{
			if((s != null) && (oControl.MinValue != null))
			{
				if(oControl.parseWith(s) < oControl.MinValue)
					s = null;
			}
			if((s != null) && (oControl.MaxValue != null))
			{
				if(oControl.parseWith(s) > oControl.MaxValue)
					s = null;
			}
		}
		if((s != null) && (oControl.IsRequired != null) && (oControl.IsRequired == true))
		{
			if(s.length == 0)
				s = null;
		}
		if((s != null) && (oControl.MinLength != null))
		{
			if(s.length < oControl.MinLength)
				s = null;
		}
				
		if((oControl.disabled == true) || (s != null))
		{
			//Don't set the control value unless it has changed.
			if((s != null) && (oControl.value != s))
				oControl.value = s;
			//Reset background color if needed.
			if(oControl.BKColor != oControl.style.backgroundColor)
				oControl.style.backgroundColor = oControl.BKColor;
			oControl.ValidFormat = true;
		}
		else
		{
			oControl.style.backgroundColor = "yellow";
			oControl.ValidFormat = false;
		}
	}
}
}

SBNet.EC.isIE = !!navigator.userAgent.toLowerCase().match(/msie/i);


//</SCRIPT>



