//*************************************************************************
//	Name : nccs.js
//	Description	: Contains generic javascript functions used in the nccs site
//	Created : 27th June, 07
//	Author : Amit Choudhary
//	Last ModiFied :	29th June, 07
//	Last ModiFied By : Amit Choudhary
//*************************************************************************

// JScript source code

//	Declaring some global variables	for holding temporary values for calculation
	var i, j, strlen; 
	var strchar = new String("");


// ============================================================================================
// Left Trim Function	
function LTrim(StringToTrim)
{
	StringToTrim = new String(StringToTrim);

//	This function trims a string from the left edge
	for(i = 0 ;i < StringToTrim.length; i++)
	{
		strchar = StringToTrim.charAt(i);
		if ( (strchar == " ") || (strchar == "\t") || (strchar == "\n") || (strchar == "\r") )
		{
			StringToTrim = StringToTrim.substr(i+1);
			i--;
		}
		else
			break;
	}
	return StringToTrim;
}

// ============================================================================================
// Right Trim Function	
function RTrim(StringToTrim)
{
	StringToTrim = new String(StringToTrim);
	
//	This function trims a string from the right edge
	for(i = StringToTrim.length - 1 ; i > -1 ; i--)
	{
		strchar = StringToTrim.charAt(i);
		if ( (strchar == " ") || (strchar == "\t") || (strchar == "\n") || (strchar == "\r") )
		{
			StringToTrim = StringToTrim.substr(0,i);
		}
		else
			break;
	}
	return StringToTrim;
}

// ============================================================================================
// Trim Function (Just calling LTrim and RTrim function in that)
function Trim(StringToTrim)
{
//	This function trims a string
//	for triming a string it will call the LTrim and RTrim function
	return  LTrim(RTrim(StringToTrim));
}

// ============================================================================================
// This Function Can Be Used To Maximize The Browser Window.
// To Do That We Need To Make A Call This Function In The window_onload() Event Of The Document
function Maximize_Window() 
{
	top.window.moveTo(0,0); 
	if (document.all) 
    { 
		top.window.resizeTo(screen.availWidth,screen.availHeight); 
	} 
	else if (document.layers || document.getElementById) 
	{ 
		if (top.window.outerHeight < screen.availHeight || top.window.outerWidth < screen.availWidth)
	    { 
			top.window.outerHeight = top.screen.availHeight; 
			top.window.outerWidth = top.screen.availWidth; 
		} 
	} 
}

// ============================================================================================
// This Functions Can Be Used To Blink The Given Text Using The <blink> tag.
// To Do So You Need To Put The Text Between <blink> & </blink> tags & Then Call
// startBlink() Function On The Onload Event Of The Page, Wbich Inturn Calls doBlink() Function
// You Can Also Set The Timing For Blinking By Specifying BlinkRate Argument.

// Example of calling : window.onload = startBlink(1000);
function doBlink()
{
  // Blink, Blink, Blink...
  var blink = document.all.tags("BLINK")
  
  var boolDisplay;
	for (var i=0; i < blink.length; i++)
	{
		if (blink[0].style.visibility == "")
		{
			boolDisplay = "hidden";
		}
		else
		{
			boolDisplay = "";
		}
		blink[i].style.visibility = boolDisplay;
	}
	if(boolDisplay == "hidden")
	{
		//doBlink();
		window.setTimeout('doBlink();',500);
	}
}

function startBlink(BlinkRate) 
{
  // Make sure it is IE4
  if (document.all)
    setInterval("doBlink()",BlinkRate)
}

//	Check the Zip code if it is invalid than
//	return false else return true  	
//	Valid Zip Code : 12345-6789-12 or 12345-6789 or 12345
function isValidZip(strZip)
{
	strZip = new String(Trim(strZip));
	strlen = strZip.length;
	if((strlen > 13) || !((strlen == 5) || (strlen == 10) || (strlen == 13)))
		return false;
	else
	{	
		for( i = 0;i < strlen ;i++)
		{
			strchar = strZip.charAt(i);
			if((i == 5 && strchar != "-") || (i == 10 && strchar != "-"))
				return false;
			if(strchar == " ")
				return false;
			if( ((i != 5) && (i != 10)) && (isNaN(strchar) == true))
				return false;
		}	
	}
	ZipArray = strZip.split("-");
	for(j = 0; j < ZipArray.length; j++)
	{
		if(ZipArray[j] < 1)
			return false;
	}
	// Valid Zip Code
	return true;
}

//	Check the Phone or Fax Number if it is invalid than 
//	return false else return true
//	Valid Phone or Fax No. : 123-456-7890

function isValidPhone_Fax(strPhone_Fax)
{
	strPhone_Fax = new String(strPhone_Fax);
	strlen = strPhone_Fax.length;
	if(strlen != 12 )
		return false;
	else
	{
		for( i = 0;i < strlen ;i++)
		{
			strchar = strPhone_Fax.charAt(i);
			if((i == 3 && strchar != "-") || (i == 7 && strchar != "-"))
				return false;
			if(strchar == " ")
				return false;
			if( ((i != 3) && (i != 7)) && (isNaN(strchar) == true))
				return false;
		}
	}
	// Valid Phone or Fax No.
	return true;
}

//	Check the Phone or Fax Number Without Area Code if 
//	it is invalid than return false else return true
//	Valid Phone or Fax No. Withou Area Code is  : 456-7890
function isValidPhone_Fax_WithOutAreaCode(strPhone_Fax)
{
	strPhone_Fax = new String(strPhone_Fax);
	strlen = strPhone_Fax.length;
	if(strlen != 8 )
		return false;
	else
	{	
		for( i = 0;i < strlen ;i++)
		{
			strchar = strPhone_Fax.charAt(i);
			if(i == 3 && strchar != "-") 
				return false;
			if(strchar == " ")
				return false;
			if( (i != 3)  && (isNaN(strchar) == true))
				return false;
		}
	}
	Phone_FaxArray = strPhone_Fax.split("-");

	for(j = 0; j < Phone_FaxArray.length; j++)
	{

	// ============================================================================================
	// The Phone/Fax Nos Containing 0000/000 (In Short Zeros) Between The Dashes 
	// Could Be Allowed As Valid Numbers

		//original condition		if(Phone_FaxArray[j] < 1)
		if(Phone_FaxArray[j] < 0)
			return false;
			
	}
	// Valid Phone or Fax No Without Area Code.
	return true;
}

//	Check the Email Address if it is invalid  than 
//	return false else return true
function isValidEmail(strEmail)
{
	var splitted = strEmail.match("^(.+)@(.+)$");
	if(splitted == null) 
		return false;
	if(splitted[1] != null )
	{
		var regexp_user=/^\"?[\w-_\.]*\"?$/;
		if(splitted[1].match(regexp_user) == null) 
			return false;
	}
	if(splitted[2] != null)
	{
		var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
		if(splitted[2].match(regexp_domain) == null) 
		{
			var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
			if(splitted[2].match(regexp_ip) == null) 
				return false;
		}
		return true;
	}
	return false;
}

//	Check the Web Address if it is invalid  than 
//	return false else return true
function isValidWebAddress(strWeb)
{
	strWeb = new String(strWeb);
	strlen = strWeb.length;
	var strFlagWebP = 0;
	var strPosWebP = 0;
	for(i = 0;i<strlen;i++)
	{
		strchar = strWeb.charAt(i);
		if(strchar == " ")
			return false;
		if(strchar == ".")
		{
			if( (i == 0))
				return false;
			strPosWebP = i;
			strFlagWebP++;
		}
	}
	//if( (strFlagWebP == 0) || ((strlen - strPosWebP) < 3) || (strPosWebP == 0) || (strPosWebP < 2) || ((strlen - strPosWebP) > 5))
	if( (strFlagWebP == 0) || ((strlen - strPosWebP) < 3) || (strPosWebP == 0) || (strPosWebP < 2) )
		return false;
	else	// Valid Web Address
		return true;
}

// ============================================================================================
//	Check the passing number for Integer value
//	if it's not an Integer number than return false else return true
function isValidInteger(strNumber)
{
	if(strNumber<0)
	{	  
		strNumber=strNumber.substring(1)  
	}   
	strNumber = new String(strNumber);
	strlen = strNumber.length;
	for( i = 0;i < strlen ;i++)
	{
		strchar = strNumber.charAt(i);
		if (isNaN(strchar) == true)
			return false;
	}
	// Valid Integer number
	return true;
}

function validateNNInteger(objControl)
{
	// Checking that the passing Number Should Be Integer And Should Be Greater Than Or Equal To 1
	
	// If The Function Is Called And The Control Is Not Exist
	// Then Simply Return From This Function
	if(!objControl)
	{
		return;
	}
	
	if(objControl.readOnly)
		return true;
		
	strNumber = objControl.value;
 	var num = BackToMoney(strNumber);
 	
 	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	
	if(parseFloat(num) < 0)
	{
		objControl.value = num;
		objControl.select();
		alert("This control cannot hold  negative number. Please re-enter your number.");
		objControl.value = "0";	
		setTimeout(function(){ objControl.focus(); objControl.select(); },1);
		return false;
	}
	
	// Valid Integer number
	objControl.value = parseInt(num);
	return true;
}

//	Convert the passing number in decimal number
//	up two two digit after decimal
function to_Decimal(strNumber)
{
	strNumber = Trim(strNumber);
	strNumber = new String(strNumber);
	
	strNumber=""+Math.round(100*strNumber);   
	var is_negative=(strNumber<0)? true:false;  
	if(is_negative)
	{	
		strNumber=strNumber.substring(1)  
	}   
	while (strNumber.length <= 2) 
	{	  
		strNumber="0"+strNumber
	}  
	var dec_point=strNumber.length-2;  
	var first_part=strNumber.substring(0,dec_point);  
	var second_part=strNumber.substring(dec_point);  
	var result=first_part+"."+second_part;  
	var sign=is_negative? "-":""; 
		
	return sign + result;
}

//	Convert the passing number to US $ currency
function to_Currency(strNumber)
{  
	if(strNumber < 0)
	{
		//return  "-" + "$" + to_Decimal(strNumber.substring(1));
		return  "-" + to_Decimal(strNumber.substring(1));
	}
	else
	{
		//return  "$" + to_Decimal(strNumber);
		return  to_Decimal(strNumber);
	}
}

// Check if passing argument is blank or not
// If that is blank than retrun true else return false
function ifBlank(str)
{
	str = new String(Trim(str));
	if (str.length==0)
		return true;
	return false;	
}

//*** Added New Functions Which Will Round Off The Given Number Upto Specified Number
//*** Of Decimal Places
function RoundDecimals(original_number, decimals) 
{
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    
    if (isNaN(result3))
		return "0.00";
	else
		return pad_with_zeros(result3, decimals);
}

function pad_with_zeros(rounded_value, decimal_places) 
{

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

function validateFLOAT(strNumber)
{
 	var num = Math.round(BackToMoney(strNumber));
    num = num.toString().replace(/\$|\,/g,'');
 	
 	if(isNaN(num))
		num = "0";
	
	if(parseFloat(num) < 0)
		sign = "-"
	else
		sign = ""
	//sign = (num == (num = Math.abs(num)));
	num = Math.abs(num);
	
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();

	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	
	num.substring(num.length-(4*i+3));
	
	var rtnValue;
	
	if(sign == "")
		rtnValue = num;
	else
		rtnValue = '-' + num;
	
	return rtnValue;
	
}

function validateNNFLOAT(objControl)
{
	// If The Function Is Called And The Control Is Not Exist
	// Then Simply Return From This Function
	if(!objControl)
	{
		return;
	}
	
	// If The Function Is Called And The Control Is Readonly
	// Then Simply Return From This Function
	if(objControl.readOnly)
		return true;
		
	strNumber = objControl.value;
//	alert ("B:strNumber = " + strNumber)
 	var num = Math.round(BackToMoney(strNumber));
//	var vName;
 	
 	num = num.toString().replace(/\$|\,/g,'');
 	
	if(isNaN(num))
		num = "0";
	
	if(parseFloat(num) < 0)
	{
		objControl.value = num;
		objControl.select();
		alert("This control cannot hold  negative number. Please re-enter your data.");
		objControl.value = "0";	
		setTimeout(function(){ objControl.focus(); objControl.select(); },1);
		return false;
	}

	num = Math.abs(num);
	
	num = Math.floor(num*100+0.50000000001);
//	cents = num%100;
	num = Math.floor(num/100).toString();

//	if(cents<10)
//		cents = "0" + cents;
	
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	
	num.substring(num.length-(4*i+3));
	
	var rtnValue;
	
//	rtnValue = num + '.' + cents;
	rtnValue = num;
	
	objControl.value = rtnValue;
//	objControl.value = Math.round(rtnValue);
	return true;
}

function validateRealNumber(strNumber)
{
	//var valid="1234567890.+-*/()%";
	var valid="1234567890.+-*/";
	var validSign = "+-*/.";
	var invalidSignFirstPos = "*/";
	var intValidSignPos, boolValidSignPos;
	intValidSignPos = 0;
	boolValidSignPos = false;
	var num = String(strNumber);
	if(num.length == 0 || invalidSignFirstPos.indexOf(num.charAt(0))!= -1 || (num.length == 1 && validSign.indexOf(num.charAt(0))!= -1) || (validSign.indexOf(num.charAt(num.length -1))!= -1) )
	{	
		num = "0";
		strNumber = 0;
	}
	var boolValid = true;
	for(i=0;i<num.length;i++)
	{
		if(valid.indexOf(num.charAt(i))==-1)
		{
			boolValid = false;
			i = num.length;
		}
		else
		{
			if(validSign.indexOf(num.charAt(i))!= -1)
			{
				if(boolValidSignPos == false)
				{
					intValidSignPos = i
					boolValidSignPos = true;
				}
				else
				{
					if(i - intValidSignPos <= 1)
					{
						boolValid = false;
						i = num.length;
					}
					else
					{
						intValidSignPos = i;
						boolValidSignPos = true;
					}
				}
			}
		}
	}
	if(boolValid == true)
	{
		strNumber = eval(num);
		return to_Decimal(strNumber);
	}
	else
	{
	
		//var floatMASK = /^-(\d{1,15})(\.\d{1,4})?$/
		var floatMASK = /^-{0,1}\d*\.{0,1}\d+$/

		var matchArray = strNumber.match(floatMASK)
		 
		if (matchArray==null)
		{
			//errMsg = "Not a valid numeric format.";
			//alert(errMsg+ ' (' + strNumber + ')');
			//isError=true
			return "0";
		}
	}
}
 
function BackToMoney(num) 
{
	num = new String(num);
	if(num.lastIndexOf('.') > 0)
	{
		if(num.lastIndexOf('.') == (num.length-1))
		{
			num = num.substr(0,(num.length-1));
		}
	}

	//	alert("num = " + num);
	num = num.toString().replace(/\$|\,/g,'');
	
	//*** The Below Code Will Calculate The Value If The Value Contain Any Of The
	//*** Four Simple Arithmetic Sign (+,-,* and /). Than That Calculate Value
	//*** Will Be Used For Further Processing.
	
	//var valid="1234567890.+-*/()%";
	var valid="1234567890.+-*/";
	var validSign = "+-*/.";
	var invalidSignFirstPos = "*/";
	var intValidSignPos, boolValidSignPos;
	intValidSignPos = 0;
	boolValidSignPos = false;
	var strnum = String(num);
	if(strnum.length == 0 || invalidSignFirstPos.indexOf(strnum.charAt(0))!= -1 || (strnum.length == 1 && validSign.indexOf(strnum.charAt(0))!= -1) || (validSign.indexOf(strnum.charAt(strnum.length -1))!= -1) )
	{	
		strnum = "0";
		num = 0;
	}
	var boolValid = true;
	for(i=0;i<strnum.length;i++)
	{
		if(valid.indexOf(strnum.charAt(i))==-1)
		{
			boolValid = false;
			i = strnum.length;
		}
		else
		{
			if(validSign.indexOf(strnum.charAt(i))!= -1)
			{
				if(boolValidSignPos == false)
				{
					intValidSignPos = i
					boolValidSignPos = true;
				}
				else
				{
					if(i - intValidSignPos <= 1)
					{
						boolValid = false;
						i = strnum.length;
					}
					else
					{
						intValidSignPos = i;
						boolValidSignPos = true;
					}
				}
			}
		}
	}	
	
	
	var arrCalc, intCalcCounter, intSignsCounter, arrSigns, strSigns;
	strSigns = new String("+,-,*,/");
	arrSigns = strSigns.split(",");
	if(boolValid == true)
		num = eval(num);
	
	//	alert("num = " + num);
	if(isNaN(num))
		num = "0";
		
	num = (Math.round(num));
//	alert("num = " + num);
	
	if(parseFloat(num) < 0)
		sign = "-"
	else
		sign = ""
	//sign = (num == (num = Math.abs(num)));
	num = Math.abs(num);
//	alert("sign = " + sign);
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num.substring(num.length-(4*i+3));
		
//	alert("num = " + num);
//	alert("cents = " + cents);
	
	var rtnValue;
	
	if(sign == "")
		rtnValue = num + '.' + cents;
	else
		rtnValue = '-' + num + '.' + cents;

//	rtnValue = num + '.' + cents;
	
//	alert(rtnValue);
	
	return rtnValue;
	
//	return (((sign)?'':'-') + num + '.' + cents);
}

function validateNumberLength(strNumber, intLen)
{
	strNumber = new String(strNumber);
	if (strNumber.length != intLen)
		return false;
	else
		return isValidInteger(strNumber);
}

function isValidCalendarYear(dtStart, dtEnd)
{
	var tempDateArray
	tempDateArray = dtStart.split("-");
	dtStart = tempDateArray.join("/");
		
	tempDateArray = dtEnd.split("-");
	dtEnd = tempDateArray.join("/");
	
	dtStart = new Date(dtStart);
	dtEnd = new Date(dtEnd);
	
	if (dtEnd <= dtStart)
		return false;
		
	var dtStartYear = dtStart.getFullYear();
	
	var dtEndYear = dtEnd.getFullYear();
	
	var isLeapFeb = (((dtStartYear % 4 == 0 && (dtStartYear % 100 != 0 || dtStartYear % 400 == 0)) && dtStart.getMonth() <= 1) || ((dtEndYear % 4 == 0 && (dtEndYear % 100 != 0 || dtEndYear % 400 == 0)) && (dtEnd.getMonth() > 1 || (dtEnd.getMonth() == 1 && dtEnd.getDate() == 29))))
	
	var DateDiff = new Date();
	
	DateDiff.setTime(Math.abs(dtEnd.getTime() - dtStart.getTime()));
	
	var TimeDiff = DateDiff.getTime();
	
	var DayDiff = Math.ceil(TimeDiff / (1000 * 60 * 60 * 24)); 
	
	//if ( (isLeapFeb == true && DayDiff != 365) || (isLeapFeb == false && DayDiff != 364))
	//	return false;
	
	if ( (isLeapFeb == true && DayDiff > 365) || (isLeapFeb == false && DayDiff > 364))
		return false;
	
	// Valid Calendar Year
	return true;
}

/*function isValidCalendarDiff(dtStart, dtEnd)
{
	var tempDateArray
	tempDateArray = dtStart.split("-");
	dtStart = tempDateArray.join("/");
		
	tempDateArray = dtEnd.split("-");
	dtEnd = tempDateArray.join("/");
	
	dtStart = new Date(dtStart);
	dtEnd = new Date(dtEnd);
	
	if (dtEnd <= dtStart)
		return false;
		
	var dtStartYear = dtStart.getFullYear();
	
	var dtEndYear = dtEnd.getFullYear();
	
	var isLeapFeb = (((dtStartYear % 4 == 0 && (dtStartYear % 100 != 0 || dtStartYear % 400 == 0)) && dtStart.getMonth() <= 2) || ((dtEndYear % 4 == 0 && (dtEndYear % 100 != 0 || dtEndYear % 400 == 0)) && dtEnd.getMonth() > 1))
	
	var DateDiff = new Date();
	var MonthDiff = new Date();
	
//	var 	MonthDiff = dtEnd.getMonth() - dtStart.getMonth();	
//	if ( (MonthDiff >= 8 ) || (MonthDiff < 0))
//		return false;
	var thisdate = new Date();
	thisdate.setDate(dtStart.getDay(), dtStart.getMonth() + 2, dtStart.getYear())
	alert(thisdate);
	
	DateDiff.setTime(Math.abs(dtStart.getTime() - dtEnd.getTime()));	
	var TimeDiff = DateDiff.getTime();
	
	var DayDiff = Math.ceil(TimeDiff / (1000 * 60 * 60 * 24)); 
	alert(DayDiff);
	
	//if ( (isLeapFeb == true && DayDiff != 365) || (isLeapFeb == false && DayDiff != 364))
	//	return false;
	
	if ( (isLeapFeb == true && DayDiff > 365) || (isLeapFeb == false && DayDiff > 364))
		return false;
	
	// Valid Calendar Year
	return true;
}*/

function isValidFullCalendarYear(dtStart, dtEnd)
{
	var tempDateArray
	tempDateArray = dtStart.split("-");
	dtStart = tempDateArray.join("/");
		
	tempDateArray = dtEnd.split("-");
	dtEnd = tempDateArray.join("/");
	
	dtStart = new Date(dtStart);
	dtEnd = new Date(dtEnd);
	
	if (dtEnd <= dtStart)
		return false;
		
	var dtStartYear = dtStart.getFullYear();
	
	var dtEndYear = dtEnd.getFullYear();
	
	var isLeapFeb = (((dtStartYear % 4 == 0 && (dtStartYear % 100 != 0 || dtStartYear % 400 == 0)) && dtStart.getMonth() <= 1) || ((dtEndYear % 4 == 0 && (dtEndYear % 100 != 0 || dtEndYear % 400 == 0)) && (dtEnd.getMonth() > 1 || (dtEnd.getMonth() == 1 && dtEnd.getDate() == 29))))
	
	var DateDiff = new Date();
	
	DateDiff.setTime(Math.abs(dtEnd.getTime() - dtStart.getTime()));
	
	var TimeDiff = DateDiff.getTime();
	
	var DayDiff = Math.ceil(TimeDiff / (1000 * 60 * 60 * 24)); 
	
	if ( (isLeapFeb == true && DayDiff != 365) || (isLeapFeb == false && DayDiff != 364))
		return false;
	
	// Valid Calendar Year
	return true;
}

//Check the passing array string for a element
//if found then return true else return false
function IsArrayContainPassingElement(arrStr, strValue)
{
	var intcounter;
	for( intcounter = 0; intcounter < arrStr.length; intcounter++)
	{
		if( String(Trim(arrStr[intcounter])).toLowerCase() ==  String(Trim(strValue)).toLowerCase() )
			return true;
	}
	return false;
}

//*** The below function will attach the specified events to the passing object
//*** This function will work on both type of browsers (IE or Netscape dervied)
function addEvent(obj, evType, fn, useCapture)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} 
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} 
	else 
	{
		alert("Handler could not be attached");
	}
} 

//*** The below function will remove the specified events from the passing object
//*** This function will work on both type of browsers (IE or Netscape dervied)
function removeEvent(obj, evType, fn, useCapture)
{
	if (obj.removeEventListener)
	{
		obj.removeEventListener(evType, fn, useCapture);
		return true;
	} 
	else if (obj.detachEvent)
	{
		var r = obj.detachEvent("on"+evType, fn);
		return r;
	} 
	else 
	{
		alert("Handler could not be removed");
	}
} 

//*** =============================================================================================
//	For getting handle of the window which show the help for a particular field
	var childWindow, childWindowWidth, childWindowHeight;
	
	if(window.screen.width < 800)
		childWindowWidth = 600;
	else
		childWindowWidth = window.screen.width - 200;
	
	if(window.screen.height < 700)
		childWindowHeight = 500;
	else
		childWindowHeight = window.screen.height - 200;
	 
//*** =============================================================================================
//	For Defining initial shape and behaviour of the new window
	var strWinProp

//*** =============================================================================================
//	Specifying initial shape and behaviour of the new window
	//	Back, Forward, etc...
	strWinProp = " toolbar=no"  
	//	URL field(Address Bar)
	+ ",location=no"			
	//	"What's New", etc...
	+ ",directories=no"			
	//	Status Bar at bottom of window.
	+ ",status=yes"				
	//	Menubar at top of window.
	+ ",menubar=no"				
	//	Allow resizing by dragging. 
	+ ",resizable=0"	//	1 = "yes", 0 = "no"		
	//	Displays scrollbars if document is larger than window.
	+ ",scrollbars=yes"			
	//	Enable/Disable titlebar resize capability.
	+ ",titlebar=yes"			
	//	Defining width of window equal to current screen width
	+ ",width="+childWindowWidth
	//	Offset of windows left edge from screen.
	+ ",left="+(((window.screen.width) - childWindowWidth)	/2)					
	//	Defining height of window equal to current screen height - 55(pixcel)
	//	so the taskbar is also visible
	+ ",height="+childWindowHeight
	//	 Offset of windows top edge from screen.
	+ ",top="+(((window.screen.height) - childWindowHeight)	/2)				
	+ "";

//*** =============================================================================================
//*** Open the child window with the specified URL passed to that
function Open_Show_childWindow(strURL)
{
	var myString = new String(strURL);
	//alert(myString);

	if(childWindow && childWindow.open && !childWindow.closed)
	{
		//*** Checking if the childWindow is exist and not closed than
		//*** replace it's location to the new Url(myString)
		//*** and set focus on it
		childWindow.location.replace(myString);
		childWindow.focus();
	}
	else
	{
		//*** childWindow is not exist so open a new window with the
		//*** specifyed Url(myString) and initial parameter (strWinProp)
		//*** and take this window's handle in to the childWindow
		//*** so we can reuse this window
		childWindow = window.open(myString,'wndChild',strWinProp); 
		childWindow.focus();
	}
	
	removeEvent(window, 'focus', window_onfocuswhilechildwinodwopen, false);
	addEvent(window, 'focus', window_onfocuswhilechildwinodwopen, false);
	
	removeEvent(window, 'unload', window_onunloadwhilechildwinodwopen, false);
	addEvent(window, 'unload', window_onunloadwhilechildwinodwopen, false);
}

//*** =============================================================================================
//*** Check the parent window focus event and if the child window 
//*** is open at that time than set the focus back to the child window
function window_onfocuswhilechildwinodwopen()
{
	if(childWindow && childWindow.open && !childWindow.closed)
	{
		//*** Checking if the childWindow is exist and not closed than
		//*** set focus on it
		childWindow.focus();
	}
}

//*** =============================================================================================
//*** Check the parent window unload event and if the child window 
//*** is open at that time than close the child window
function window_onunloadwhilechildwinodwopen()
{
	if(childWindow && childWindow.open && !childWindow.closed)
	{
		//*** Checking if the childWindow is exist and not closed than
		//*** close it
		childWindow.close();
	}
}

//*** =============================================================================================
//*** Check the child window unload event and if the parent window 
//*** is open at that time than set focus to the parent window
function window_onunloadwhileparentwinodwopen()
{
	if(opener && opener.open && !opener.closed)
	{
		//*** Checking if the parent Window is exist and not closed than
		//*** set focus on that when child window is about to unload
		//*** set the focus on the parent window after 10  
		opener.focus();
		//setTimeout("opener.focus()", 100);
	}
}

//*** =============================================================================================
//*** This function will set the tab order on a form this function also checks before setting the 
//*** tab order on the form  that on which control has the focus when this function is called if 
//*** the function fined any active control than after setting the tab  order it set the focus 
//*** on that control

function ReadOnlyTabFalse(frm)
{
	var boolFocus = false;
	var objControl;
	if(document.activeElement.name != null)
	{
		var strName = new String(document.activeElement.name);
		strName = Trim(strName);
		if(strName.length > 0)
		{
			boolFocus = true;
			objControl = document.activeElement;
		}
	}	
	
	if(document.activeElement.id != null && boolFocus == false)
	{
		var strId = new String(document.activeElement.id);
		strId = Trim(strId);
		if(strId.length > 0)
		{
			boolFocus = true;
			objControl = document.activeElement;
		}	
	}	
	
	var tshow, thidden;
	tshow=1;
	thidden=0;
	var useragent = navigator.userAgent;
	var bName = (useragent.indexOf('Opera') > -1) ? 'Opera' : navigator.appName;
	
	var pos = useragent.indexOf('MSIE');
	if (pos > -1)
	{
		tshow = 0;
		thidden = -1;
	}	
	
	var frmname = document.forms[frm]
	
	//*** Check the form is exist or not when this function is called.....
	//*** Many time this function get called when the window is still not properly loaded...
	//*** In that case an error occured...to prevent that added the condition which check that
	//*** form is exist or not and if it than execute the code...
	
	if(typeof(frmname) != "undefined" && frmname != null )
	{
		DateBtnFocus(frmname);
		for (i=0;i<frmname.elements.length;i++)
		{
			//if ((frmname.elements[i].readOnly==true) || (frmname.elements[i].disabled==true) || (frmname.elements[i].style.visibility=='hidden'))
			if ((frmname.elements[i].readOnly==true) || (frmname.elements[i].style.visibility=='hidden'))
			{
				frmname.elements[i].tabIndex=thidden;
			}
			else
			{
				frmname.elements[i].tabIndex=tshow;
				//tshow = tshow + 1;
			}
		}
	}
	
	//*** If boolFocus is true that means when this function is 
	//*** called a control has the focus so set the focus back to that control
	
	if(boolFocus)
	{
		if(objControl.type == "text")
		{
			objControl.focus();
			objControl.select();
		}
	}
}

//*** ********************************************************************************
//*** This function Check Full EIN no. is valid or not.
//*** if user not Enter Ein or Entered Invalid Ein then Function return an Error message
//*** ********************************************************************************
function validateFullEin(strEin)
{
	var strError = '';
	if (/^\d\d-\d\d\d\d\d\d\d$/.test(strEin))
	{
		return strError;
	}

	matches =/^(\d\d)(\d\d\d\d\d\d\d)$/.exec(strEin);
	if (matches)
	{
		strEin = matches[1] + '-' + matches[2];
		return strError;
	}

	strError = "\nEin number must be 10 characters long in the format NN-NNNNNNN.";  
	return strError;
}

//*** This function will replace carriage returns in passing object value to spaces
function changeStringRE(obj) 
{
	var strDes = obj.value;
	if (strDes.match(/\n/) || strDes.match(/\r/) ){
		strDes = strDes.replace(/\n\r/g,' ');
		strDes = strDes.replace(/\r\n/g,' ');
		strDes = strDes.replace(/\n/g,' ');
		strDes = strDes.replace(/\r/g,' ');
		obj.value = strDes;
	}
	// alert( obj.name + ' - ' + obj.value + '(end)');
}

//*** =====================================================================================
//*** Function Which Will Check That The Passing Date's Day Is The
//*** Last Month Of That Month Or Not
function islastdayofmonth(mdy)
{
	var dd,mm,yy;
	var strdate = new Date(mdy)

	dd = strdate.getDate();
	mm = strdate.getMonth() + 1;
	yy = strdate.getFullYear();

	switch(mm)
	{
		case 1:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 2:
			if ((yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0))
			{
				if (dd == '29')
					return true;
				else
					return false;
			}
			else
			{
				if (dd == '28')
					return true;
				else
					return false;
			}
			break;
		case 3:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 4:
			if (dd == '30')
				return true;
			else
				return false;
			break;
		case 5:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 6:
			if (dd == '30')
				return true;
			else
				return false;
			break;
		case 7:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 8:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 9:
			if (dd == '30')
				return true;
			else
				return false;
			break;
		case 10:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		case 11:
			if (dd == '30')
				return true;
			else
				return false;
			break;
		case 12:
			if (dd == '31')
				return true;
			else
				return false;
			break;
		default:
			alert('Invalid Month Number');
	}
}

//*** =====================================================================================
//*** This function Replace some Special character like EM Dash, CRLF, Continious
//*** Space etc..

function ReplaceSpChar(obj)
{   
    var strval;
    strval = new String(obj.value);
	//alert(strval);
    var i;
    for (i=0;i<strval.length;i++)  
    {
     //   alert(strval.charCodeAt(i));
        if(strval.charCodeAt(i) == 8220)  
		{	
		    strval = strval.replace(String.fromCharCode(8220),"\"");   // Replace (“) with (")
        }
        
        if(strval.charCodeAt(i) == 8221)  
		{	
		    strval = strval.replace(String.fromCharCode(8221),"\"");   // Replace (”) with (")
        }
        
        if(strval.charCodeAt(i) == 8216)  
		{	
		    strval = strval.replace(String.fromCharCode(8216),"'");   // Replace (‘) with (")
        }
        
        if(strval.charCodeAt(i) == 8217)  
		{	
		    strval = strval.replace(String.fromCharCode(8217),"'");   // Replace (’) with (")
        }
        
        if(strval.charCodeAt(i) == 9)  // Replace Tab with Space.
		{	
		    strval = strval.replace(String.fromCharCode(9)," ");  
        }
        if(strval.charCodeAt(i) == 8211)  // Replace DmDash with Dash.
		{	
		    strval = strval.replace(String.fromCharCode(8211),"-");  
        }
        if(strval.charCodeAt(i) == 13)  // Replace CrLf with Space.
		{	
			strval = strval.replace(String.fromCharCode(13) + String.fromCharCode(10)," ");
		}
		if (strval.charCodeAt(i) == 10)  // Replace CrLf with Space.
		{
		    strval = strval.replace(String.fromCharCode(10)," ");
		}
		if (strval.charCodeAt(i) == 8226)  // Replace "." (A Bullet)with "*".
		{
		    strval = strval.replace(String.fromCharCode(8226),"*");
		}
	}
    strval = Trim(strval);
    var regexp = /  /g;
    while (strval.match(regexp))
    {
        strval = strval.replace(regexp," ");  // Replace Continious two or more spaces.
    } 
    obj.value = strval;
    
}

//*** =====================================================================================
//*** This function checks weather Browser is IE or Netscape.
function CheckBrowser()
{
    var browserName=navigator.appName; 
    if (browserName=="Netscape")
    { 
        return "Netscape";
    }
    else if(browserName=="Microsoft Internet Explorer")
    {
        return "IE";      
    }
}

//*** =====================================================================================
//*** This function will count all the checkbox which are checked on a form (which name 
//*** passed in this function and if their ids are same as the id passed to it)
function getCheckCount(id, frm)
{	
	var intCount=0;

    for(i=0;i < eval("document." + frm + ".elements.length");i++)
    {	
		if (eval("document." + frm + ".elements[" + i + "].id") == id && eval("document." + frm +".elements[" + i + "].checked") == true) 
		    intCount++;
    }
    return intCount;
}

//*** =====================================================================================
//*** This function will check all the checkbox which are checked on a form (which name 
//*** passed in this function and if their ids are same as the id passed to it) and then 
//*** take their values and join them using comma and return that string with comma seprated 
//*** checked checkboxes value
function getCheckValues(id, frm)
{	
	var strValues = new String("");

    for(i=0;i < eval("document." + frm + ".elements.length");i++)
    {	
		if (eval("document." + frm + ".elements[" + i + "].id") == id && eval("document." + frm +".elements[" + i + "].checked") == true) 
		    strValues = strValues + "," + eval("document." + frm + ".elements[" + i + "].value");
    }
    
	if(strValues.length > 0)
    	strValues = strValues.substring(1, strValues.length);
    	
    return strValues;
}

//*** =====================================================================================
//*** This function will show all the controls which are on a form (which name 
//*** passed in this function and if their ids are same as the id passed to it)
function showControlsWithSpecificID(id, frm)
{	
	for(i=0;i < eval("document." + frm + ".elements.length");i++)
    {	
		if (eval("document." + frm + ".elements[" + i + "].id") == id) 
		    eval("document." + frm + ".elements[" + i + "].style.display = 'inline';");
    }
}

//*** =====================================================================================
//*** Added By Amit On 29th June, 07
//*** A useful object and set of properties for detecting the browser and other 
//*** things about user system (browser name, browser primary version and OS name)

//*** You can query three properties of the BrowserDetect object:

//*** Browser name: BrowserDetect.browser
//*** Browser version: BrowserDetect.version
//*** OS name: BrowserDetect.OS

//*** =====================================================================================

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "An unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
	    //alert(dataString);
	    //alert(this.versionSearchString);
		var index = dataString.indexOf(this.versionSearchString);
		//alert(index);
		if (index == -1) return;
		//alert(dataString.substring(index+this.versionSearchString.length+1));
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		//return dataString.substring(index+this.versionSearchString.length+1);
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Mozilla Firefox",
			versionSearch: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Microsoft Internet Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
//*** Create the BrowserDetect object by calling the initialize (init) method
BrowserDetect.init();

//*** =====================================================================================
//*** End Of Addition By Amit On 29th June, 07
//*** =====================================================================================

function checkdate(inputOBJ)
{
	//Basic check for format validity
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/; 
	var returnval= new String("");
	if (!validformat.test(inputOBJ.value))
	{
		returnval= "Invalid Date Format.";
	}
	else
	{ //Detailed check for valid date ranges
		var monthfield=inputOBJ.value.split("/")[0];
		var dayfield=inputOBJ.value.split("/")[1];
		var yearfield=inputOBJ.value.split("/")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
			returnval= "Invalid Day, Month, or Year range detected.";
		else
			returnval="";
	}
	return returnval;
}