﻿var TEXTCASE_NORMAL = "";
var TEXTCASE_UPPER = "upper";
var TEXTCASE_LOWER = "lower";
//
var TEXT_ENTRY_TYPE_NUMERIC = "numeric";
var TEXT_ENTRY_TYPE_ALPHANUMERIC = "alphanumeric";
var TEXT_ENTRY_TYPE_PHONE = "phone";
var TEXT_ENTRY_TYPE_EMAIL = "email";
var TEXT_ENTRY_TYPE_FILENAME = "file"; var TEXT_ENTRY_TYPE_FILENAME_INVALID_CHARS = "\\/<>;:?*\"|";
var TEXT_ENTRY_TYPE_ABN = "abn";
var TEXT_ENTRY_TYPE_SPECIAL_CHARACTER = "!@#$%^\&*()_-+=<;[]{ },.\/?\\|'`\"~";
//
function initTextBox(elm)
{
	if (window._textBoxFunctions == null) {
		window._textBoxFunctions =
		{
			getEnabled: function ()		{return !this.disabled;},
			setEnabled: function (val)	{this.disabled = !val;},

			getReadOnly: function ()		{return this.readOnly;},
			setReadOnly: function (val) 
			{
				if (val != this.getReadOnly())
				{
					if (val)
						with (this) {readOnly = true; this._tabIndex = tabIndex; tabIndex = -1; className += " ReadOnly"}
					else
						with (this) {readOnly = false; tabIndex = this._tabIndex; className = className.replace("ReadOnly", "");}
				}		
			},

			getInitValue: function()	{return this.getAttribute("initValue");},
			setInitValue: function(val)	{this.setAttribute("initValue", val != null ? val : "");},

			getValue: function()		{return this.value;},
			setValue: function(val)		{this.value = val ? val : "";},

			getTextCase: function()		{return this.getAttribute("textcase") ? this.getAttribute("textcase") : TEXTCASE_NORMAL},
			setTextCase: function(val)	{this.setAttribute("textcase", val);},

			clear: function()			{this._cachedValue = this.getValue(); this.setValue("");},
			reset: function()			{this.setValue(this.getInitValue());},
			restore: function()			{if (this._cachedValue != null) this.setValue(this._cachedValue);},

			isEmpty: function ()		{return (!this.value);},

			isValid: function(entryType, isRequired)	
			{
				if (!entryType && this._numericInput)
					entryType = TEXT_ENTRY_TYPE_NUMERIC;
		
				var val = this.getValue();		
				if (!val)
					return !isRequired;			
			
				switch (entryType)
				{			
					case TEXT_ENTRY_TYPE_ALPHANUMERIC:
						var regExp = /[a-zA-Z0-9\s]+$/;
						return regExp.test(val);
				
					case TEXT_ENTRY_TYPE_NUMERIC:
					case TEXT_ENTRY_TYPE_PHONE:				
						var regExp = /[^\d ]/;
						return !regExp.test(val);		
				
					case TEXT_ENTRY_TYPE_EMAIL:
						if (!val.contains("@") || val.getCharCount("@") > 1 
							|| val.contains(",") 
							|| val.contains(" ")
							|| val.beginsWith("@") || val.endsWith("@")
							|| val.beginsWith(".") || val.endsWith("."))
							return false;				
						else
						{
							var valid = true;
							
							var pos = val.indexOf("@");
							if (pos + 4 > val.length)
								return false;
														
							valid = !val.substr(pos + 1, 1).contains(".");
							
							if(valid)
							{ 
								var emailRegExp = /^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/					
								var reg = new RegExp(emailRegExp);
								valid = reg.test(val);
							}
							
							return valid;
						}					
					
					case TEXT_ENTRY_TYPE_FILENAME:		
						for (var i = 0; i < val.length; i++)
							if (TEXT_ENTRY_TYPE_FILENAME_INVALID_CHARS.indexOf(val.charAt(i)) >= 0)
								return false;
						return true;	
					
					case TEXT_ENTRY_TYPE_ABN:
						if (!this.isValid(TEXT_ENTRY_TYPE_NUMERIC))
							return false;
						else if (this.getValue().length != 9 && this.getValue().length != 11)
							return false;
						else if (this.getValue().length == 11)	
						{					
							var sum = 0; var weights = new Array(10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19);						
							for (var i = 0; i < 11; i++)
							{
								var digit = castInt(this.value.charAt(i));
								if (i == 0)
									digit--;
								sum += (digit * weights[i]);	
							}
							return (sum % 89 == 0);
						}					
						return true;	
						
					default: 
						return true;
				}
			},

			showBorder: function (val)
			{
				if (!val)
					this.className += " NoBorder";
				else	
					this.className = this.className.replace("NoBorder", "");
			},

			setFocus: function() 
			{
				try
				{
					this.focus();
					if (this.onfocus)
						this.onfocus();			
				} 
				catch(e){}
			},

			setOnFocusHandler: function(handler) {this._onFocusHandler = handler;},
			onfocus: function(eventObj) 
			{		
				try 
				{
					if (this._onFocusHandler)		
						this._onFocusHandler();
					
					if (!this.getReadOnly() && this.value) 
						this.select();							
				} 
				catch(e) {displayErr("TextBox_OnFocus", e);}
			},

			onchange: function() 
			{
				if (this._onChangeHandler)
					window.postAction("try {" + this.id + "._onChangeHandler(); } catch(e) {displayErr('TextBox_OnChange', e);}");		
			},

			onkeypress: function(eventObj)
			{
				try 
				{
					eventObj = extendEventObj(eventObj);	
					var canAdjTextCase = false;	
					var textCase = this.getTextCase();
					//
					if(this._numericInput)
					{
						
						var chrCode = eventObj.charCode;
						if (chrCode >= 48 && chrCode <= 57)
							this.onchange();
						else if (chrCode != 0)
							eventObj.cancelDefault(); 
					
					}
					else if(this._execludeSymbols)
					{
						
						var chrCode = eventObj.charCode;
						var character = String.fromCharCode(chrCode);
						var regex = /^[a-zA-Z0-9\040\',.]+$/;
						
						
						
						if(regex.test(character))
							this.onchange();
						else
							eventObj.cancelDefault(); 
					
					}
					else
					{
						if (isIE || isFF)
						{
							this.onchange();
							if (eventObj.keyCode == 13)
								eventObj.cancelDefault(); 						
							else		
								canAdjTextCase = true;
						}	
						else if (eventObj.isChar)
						{				
							if (!_keyCodesReportedAsChrInNS.contains(eventObj.keyCode))
							{
								this.onchange();
								canAdjTextCase = true;
							}	
							else
							{
								if (eventObj.keyCode == 46)
									this.onchange();
							}	
						}				
						//			
						if (canAdjTextCase && textCase != TEXTCASE_NORMAL)
						{
							var chrCode = eventObj.charCode;
							if (textCase == TEXTCASE_LOWER)
								chrCode = String.fromCharCode(chrCode).toLowerCase().charCodeAt(0);
							else	
								chrCode = String.fromCharCode(chrCode).toUpperCase().charCodeAt(0);
							if (isIE)
								eventObj.keyCode = chrCode;
							else
							{	
							/*
								return; // some problem with NS7
													
								eventObj.cancelDefault(); 
								//
								var eventNew = document.createEvent("KeyEvents");
								eventNew.initKeyEvent("keypress", true, true, null, false, false, false, false, 0, chrCode);
								this.dispatchEvent(eventNew);
								*/
							}			
						}
					
					}
				
					//
					if (this._onKeyPressHandler) 
						this._onKeyPressHandler(eventObj);
				}
				catch(e) {displayErr("TextBox_OnKeyPress", e);}
			},

			onkeyup: function(eventObj)
			{			
				try 
				{
					eventObj = extendEventObj(eventObj);		
					switch (eventObj.keyCode)
					{
						case 8: case 46:	// Backspace,Delete 
							this.onchange(); 
							break;
					}
				}
				catch(e) {displayErr("TextBox_OnKeyUp", e);}
			},
			
			test: function () {},
			
			getAutoComplete: function()		
			{
				if(this.getAttribute("autocomplete") != null)
					return this.getAttribute("autocomplete") == "on" ? "on" : "off";
				else
					return "none";
				
			},
			setAutoComplete: function(val)	
			{
				if(val != "none" && val != null)				
					this.setAttribute("autocomplete", val == "on" ? "on" : "off");			
			}
			
			
		};
	}

	var initOnFocusHandler = elm._onFocusHandler;
	var initOnChangeHandler = elm._onChangeHandler;
	var initOnKeyPressHandler = elm._onKeyPressHandler;

	// add interfaces
	elm = extendElement(elm);
	elm = Object.extend(elm, window._textBoxFunctions);
	
	// initialize
	elm._numericInput = castBool(elm.getAttribute("numericInput"));
	elm._execludeSymbols = castBool(elm.getAttribute("exSymbols"));

	// auto event wire up
	elm._onFocusHandler = initOnFocusHandler ? initOnFocusHandler : getEventHandler(elm.id, "OnFocus");
	elm._onChangeHandler = initOnChangeHandler ? initOnChangeHandler : getEventHandler(elm.id, "OnChange");
	elm._onKeyPressHandler = initOnKeyPressHandler ? initOnKeyPressHandler : getEventHandler(elm.id, "OnKeyPress");

	//
	if (!elm._onChangeHandler)
		elm._onChangeHandler = elm.onchange; // !!!		
	
	return elm;
}
