//Global XMLHTTP Request object
var XmlHttp;
var myTxt;
//var decimalPoint='';
//var millPoint='';
var pos;
var countMillPoints=0;
var countMillPointsOld=1;
var strCheck = '0123456789';
var CurrentValue="";

//regular expressions
var decimalPointRE;
var millPointRE;

var sPath = window.location.pathname;
var sPathArray = new Array();
sPathArray = sPath.split('/');
//get IIS root folder
var APP_ROOT = "";
if (sPathArray[0] != "") {
    APP_ROOT = '/' + sPathArray[0] + '/';
}
else {
    APP_ROOT = '/' + sPathArray[1] + '/';
}

var AJAX_FILE_PATH_NUM = APP_ROOT + "Scripts/NumTextBox/";

//Creating and setting the instance of appropriate XMLHTTP Request object to a “XmlHttp” variable  
function CreateXmlHttp()
{
	//Creating object of XMLHTTP in IE
	try
	{
		XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttp = null;
		}
	}
	//Creating object of XMLHTTP in Mozilla and Safari 
	if(!XmlHttp && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttp = new XMLHttpRequest();
	}
}

//Gets called when MeasType ddl box selection changes
function getCurrentDecimal(txt, hasDecimals, hasMills, decimalPlaces) 
{
	//this is needed to store in the cache a different page for every page call 
	//so that XML files do not get mixed up!
	var CurrentDateTime = document.lastModified;
	myTxt = document.getElementById(txt);
	
	CurrentValue = myTxt.value;//empty string
	
		// URL to get conditions for a given base
	var requestUrl = AJAX_FILE_PATH_NUM + "AjaxServerNumeric.aspx" + "?CurrentValue=" + encodeURIComponent(CurrentValue) +
		"&decimalPlaces="+encodeURIComponent(decimalPlaces) + "&hasDecimals="+encodeURIComponent(hasDecimals) +
		"&hasMills="+encodeURIComponent(hasMills) + 
		"&CurrentDateTime="+CurrentDateTime;
		
		CreateXmlHttp();
		
		// If browser supports XMLHTTPRequest object
		if(XmlHttp)
		{
			//Setting the event handler for the response
			XmlHttp.onreadystatechange = function() {
				// To make sure receiving response data from server is completed
				if(XmlHttp.readyState == 4)
				{
					// To make sure valid response is received from the server, 200 means response received is OK
					if(XmlHttp.status == 200)
					{
						myTxt.value = XmlHttp.responseText;
						
						if(strCheck.indexOf(myTxt.value.substring(5,6)) == -1)
						{
							decimalPoint=myTxt.value.substring(5,6);
						}
						else// if(myTxt.value.indexOf('.')>-1)
						{
							decimalPoint='';
						}

						if(strCheck.indexOf(myTxt.value.substring(1,2)) == -1)
						{
							millPoint=myTxt.value.substring(1,2);
						}
						else// if(myTxt.value.indexOf('.')>-1)
						{
							millPoint='';
						}
						
						//re-initialize textbox value
						myTxt.value=CurrentValue;
						
						//Construct the regular expressions
						decimalPointRE = new RegExp("["+decimalPoint.toString()+"]", 'gi');
						millPointRE = new RegExp("["+millPoint.toString()+"]", 'gi');
					}
					else
					{
						//alert("There was a problem retrieving data from the server." );
					}
				};
			};
			
			//Initializes the request object with GET (METHOD of posting), 
			//Request URL and sets the request as synchronous.
			XmlHttp.open("GET", requestUrl,  false);
			
			//Sends the request to server
			XmlHttp.send(null);		
		}
	
}


// These functions ONLY work on MSIE (Win) 
// Gets Cursor Position by comparing to a moving text range. 
function GetCursorPosition() { 
  var obj = document.activeElement; 
  var cur = document.selection.createRange(); 
  pos = 0; 
  if (obj && cur) { 
    var tr = obj.createTextRange(); 
    if (tr) { 
      while (cur.compareEndPoints("StartToStart", tr) > 0) { 
        tr.moveStart("character", 1); 
        pos++; 
      } 
      return pos; 
    } 
  } 
  return -1; 
} 

// Sets Cursor Position by creating a new text range and moving it 
function SetCursorPosition(pos) { 
  var obj = document.activeElement; 
  if (obj) { 
    var tr = obj.createTextRange(); 
    if (obj && tr) { 
      tr.moveStart("character", pos); 
      tr.collapse(); 
      tr.select(); 
      return true; 
    } 
  } 
  return false; 
} 

function numOnly(e)
{
	//the user can enter only numbers
	
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13 || whichCode == 9) return true; //if the user hits the Enter or Tab key
	if (whichCode == 8 || whichCode == 46) return true; //if the user hits the backspace or delete key
	if (whichCode > 36 && whichCode < 41) return true; //if the user hits the Arrow keys
	key = String.fromCharCode(whichCode);
	if (strCheck.indexOf(key) == -1) return false;
}

function fnPaste()
{
	var valueIsNumeric=true;
	var pasteData = window.clipboardData.getData("Text");
	if(pasteData.length > 0)
	{
	
		//*** USE THE FOLLOWING CODE IF YOU WANT TO REPLACE ALL NON-NUMERIC VALUES AND PASTE THE NUMBERS ONLY ***//
//			var decs = new Array();
//			var mills = new Array();
//		
//			decs = pasteData.split(decimalPoint);
//			var newValue="";
//			var newValue2="";
//			var cleanValue="0";
//			for(i=0;i<decs.length;i++)
//			{
//				newValue+=decs[i].toString();
//			}
//			mills = newValue.split(millPoint);
//			for(i=0;i<mills.length;i++)
//			{
//				newValue2+=mills[i].toString();
//			}
//		
//			//check if the value contains any non-numeric characters and remove them
//			for(i=0;i<newValue2.length;i++)
//			{
//				if(isNaN(newValue2.charAt(i)) || newValue2.charAt(i)==' ') //space is not NaN so we have to check for that too
//				{
//				}
//				else
//				{
//					cleanValue+=newValue2.charAt(i);
//				}
//			
//				//parse the value as integer
//				pasteData = parseInt(cleanValue,10).toString();
//			}
//			//*** USE THE ABOVE CODE IF YOU WANT TO REPLACE ALL NON-NUMERIC VALUES AND PASTE THE NUMBERS ONLY ***//

		//*** COMMENT OUT THIS CODE IF YOU ONLY WANT TO USE ABOVE CLAW ***//
		//var decimalPointRE = new RegExp(decimalPoint.toString(), 'gi');
		//var millPointRE = new RegExp(millPoint.toString(), 'gi');
				
		pasteData=pasteData.replace(decimalPointRE,'').replace(millPointRE,'').replace(/ /gi,'');//spaces must be removed manually even if a separator is *space* (don't understand why! CC))
		//*** COMMENT OUT THIS CODE IF YOU ONLY WANT TO USE ABOVE CLAW ***//
	}
	
	//check if the value contains any non-numeric characters
	for(i=0;i<pasteData.length;i++)
	{
		if(isNaN(pasteData.charAt(i)))
		{
			valueIsNumeric=false;
		}
		else
		{
		}
	}

	if(!valueIsNumeric)
	{
		alert('Text: ' + pasteData + ' \n\nThe text you are trying to copy contains non numeric characters.')
		return false;
	}
	else
	{
		return true;
	}

}
function getNumber(txt, hasDecimals, hasMills, decimalPlaces)
{
	myTxt = document.getElementById(txt);
	var CurrentValue = myTxt.value;

	if(myTxt.readOnly==false)
	{
		if(hasDecimals && hasMills)
		{
			GetCursorPosition();
			if(CurrentValue.length > 0)
			{				
				var newValue=CurrentValue.replace(decimalPointRE,'').replace(millPointRE,'').replace(/ /gi,'');
				
				//parse the value as integer in order to remove leading zeros
				//CurrentValue = parseInt(newValue,10).toString();
				
				//remove leading zeros - the reason for not parsing the value is because javascript can only parse
				//up to 17 digits, then it writes the number in exponential form
				CurrentValue = newValue.replace(/^[0]+/g,"");
					
				if(CurrentValue!="0" || CurrentValue!="")
				{
					if(CurrentValue.length>decimalPlaces)
					{
						var CurrentValueNoDecimals = CurrentValue.substring(0,CurrentValue.length-decimalPlaces);
						
						if(CurrentValueNoDecimals.length<4)
						{
							countMillPoints=0;
							
							CurrentValue = CurrentValueNoDecimals + decimalPoint + 
										CurrentValue.substring(CurrentValue.length-decimalPlaces);
						}
						else
						{
							var CurrentValueMillsNoDecimals="";
							countMillPoints=0;
							for(c = CurrentValueNoDecimals.length-1; c > -1; c --)
							{
								m=CurrentValueNoDecimals.length-1-c;
								if((m) % 3 == 0)
								{
									countMillPoints++;
									CurrentValueMillsNoDecimals=millPoint+CurrentValueMillsNoDecimals;
								}
								CurrentValueMillsNoDecimals=CurrentValueNoDecimals.charAt(c)+CurrentValueMillsNoDecimals;
							}
							
							if(CurrentValueMillsNoDecimals.substring(CurrentValueMillsNoDecimals.length-1,CurrentValueMillsNoDecimals.length)==millPoint)
							{
								CurrentValueMillsNoDecimals = CurrentValueMillsNoDecimals.substring(0,CurrentValueMillsNoDecimals.length-1);
							}
							
							CurrentValue = CurrentValueMillsNoDecimals+decimalPoint+
										CurrentValue.substring(CurrentValue.length-decimalPlaces);
							
						}
					}
					else if(CurrentValue.length<decimalPlaces)
					{
						pos+=decimalPlaces+1;
						
						var decimalDigits="";
						for(i=0;i<(decimalPlaces-CurrentValue.length);i++)
						{
							decimalDigits+="0";
						}
						CurrentValue = "0"+decimalPoint+decimalDigits+CurrentValue;
					}
					else
					{
						pos++;
						CurrentValue = "0"+decimalPoint+CurrentValue;
					}
					
					//adjust cursor position for mill separator changes
					if(countMillPointsOld==1)// first time the app is used, the mill sep is set to 1
					{
					}
					else if(countMillPoints>countMillPointsOld)
					{
						pos++;
					}
					else if(countMillPoints<countMillPointsOld)
					{
						pos--;
					}
							
					countMillPointsOld=countMillPoints;
					
					myTxt.value=CurrentValue;
					SetCursorPosition(pos);
					return false;
				}
				else
				{
					var decimalDigits="";
					for(i=0;i<decimalPlaces;i++)
					{
						decimalDigits+="0";
					}
					CurrentValue = "0"+decimalPoint+decimalDigits;
					
					myTxt.value=CurrentValue;
					//SetCursorPosition(pos);
					return false;
				}
			}
			else
			{
				var decimalDigits="";
				for(i=0;i<decimalPlaces;i++)
				{
					decimalDigits+="0";
				}
				CurrentValue = "0"+decimalPoint+decimalDigits;
				
				myTxt.value=CurrentValue;
				//SetCursorPosition(pos);
				return false;
			}
		}
		else if(hasDecimals)
		{
			GetCursorPosition();
			if(CurrentValue.length > 0)
			{
				var newValue=CurrentValue.replace(decimalPointRE,'').replace(millPointRE,'').replace(/ /gi,'');
				
				//parse the value as integer in order to remove leading zeros
				//CurrentValue = parseInt(newValue,10).toString();
				
				//remove leading zeros - the reason for not parsing the value is because javascript can only parse
				//up to 17 digits, then it writes the number in exponential form
				CurrentValue = newValue.replace(/^[0]+/g,"");
				
				if(CurrentValue!="0" || CurrentValue!="")
				{
					if(CurrentValue.length>decimalPlaces)
					{
						var CurrentValueNoDecimals = CurrentValue.substring(0,CurrentValue.length-decimalPlaces);
						var CurrentValueDecimals = CurrentValue.substring(CurrentValue.length-decimalPlaces);
						
						CurrentValue = CurrentValueNoDecimals + decimalPoint + CurrentValueDecimals;
					}
					else if(CurrentValue.length<decimalPlaces)
					{
						pos+=decimalPlaces+1;
						
						var decimalDigits="";
						for(i=0;i<(decimalPlaces-CurrentValue.length);i++)
						{
							decimalDigits+="0";
						}
						CurrentValue = "0"+decimalPoint+decimalDigits+CurrentValue;
					}
					else
					{
						pos++;
						CurrentValue = "0"+decimalPoint+CurrentValue;
					}

					myTxt.value=CurrentValue;
					SetCursorPosition(pos);
					return false;
				}
				else
				{
					var decimalDigits="";
					for(i=0;i<decimalPlaces;i++)
					{
						decimalDigits+="0";
					}
					CurrentValue = "0"+decimalPoint+decimalDigits;
					
					myTxt.value=CurrentValue;
					//SetCursorPosition(pos);
					return false;
				}
			}
			else
			{
				var decimalDigits="";
				for(i=0;i<decimalPlaces;i++)
				{
					decimalDigits+="0";
				}
				CurrentValue = "0"+decimalPoint+decimalDigits;
				
				myTxt.value=CurrentValue;
				//SetCursorPosition(pos);
				return false;
			}
		}
		else if(hasMills)
		{
			GetCursorPosition();
			if(CurrentValue.length > 0)
			{
				var newValue=CurrentValue.replace(decimalPointRE,'').replace(millPointRE,'').replace(/ /gi,'');
				
				//parse the value as integer in order to remove leading zeros
				//CurrentValue = parseInt(newValue,10).toString();
				
				//remove leading zeros - the reason for not parsing the value is because javascript can only parse
				//up to 17 digits, then it writes the number in exponential form
				CurrentValue = newValue.replace(/^[0]+/g,"");
				
				if(CurrentValue!="0" || CurrentValue!="")
				{
					if(CurrentValue.length<4)
					{
						countMillPoints=0;
						
						CurrentValue = CurrentValue;
					}
					else
					{
						var CurrentValueMillsNoDecimals="";
						countMillPoints=0;
						for(c = CurrentValue.length-1; c > -1; c --)
						{
							m=CurrentValue.length-1-c;
							if((m) % 3 == 0)
							{
								countMillPoints++;
								CurrentValueMillsNoDecimals=millPoint+CurrentValueMillsNoDecimals;
							}
							CurrentValueMillsNoDecimals=CurrentValue.charAt(c)+CurrentValueMillsNoDecimals;
						}
						
						if(CurrentValueMillsNoDecimals.substring(CurrentValueMillsNoDecimals.length-1,CurrentValueMillsNoDecimals.length)==millPoint)
						{
							CurrentValueMillsNoDecimals = CurrentValueMillsNoDecimals.substring(0,CurrentValueMillsNoDecimals.length-1);
						}
						
						CurrentValue = CurrentValueMillsNoDecimals;
						
					}
				
					//adjust cursor position for mill separator changes
					if(countMillPointsOld==1)// first time the app is used, the mill sep is set to 1
					{
					}
					else if(countMillPoints>countMillPointsOld)
					{
						pos++;
					}
					else if(countMillPoints<countMillPointsOld)
					{
						pos--;
					}
							
					countMillPointsOld=countMillPoints;
					
					myTxt.value=CurrentValue;
					SetCursorPosition(pos);
					return false;
				}
				else
				{
					CurrentValue = "0";
					
					myTxt.value=CurrentValue;
					//SetCursorPosition(pos);
					return false;
				}
			}
			else
			{
				
				CurrentValue = "0";
				
				myTxt.value=CurrentValue;
				//SetCursorPosition(pos);
				return false;
			}
		}
		else
		{
			if(CurrentValue.length > 0)
			{
				GetCursorPosition();
				var newValue=CurrentValue.replace(decimalPointRE,'').replace(millPointRE,'').replace(/ /gi,'');
				
				//parse the value as integer in order to remove leading zeros
				//CurrentValue = parseInt(newValue,10).toString();
				
				//remove leading zeros - the reason for not parsing the value is because javascript can only parse
				//up to 17 digits, then it writes the number in exponential form
				CurrentValue = newValue.replace(/^[0]+/g,"");
				
				myTxt.value=CurrentValue;
				SetCursorPosition(pos);
				//do nothing - write digits as the user types
			}
		}
	}
}
