
//////////////////////////////////////////////////////////////////////////////////////////
// This JS file contains some commonly used utility functions
// Last modified on 19 Aug 2004 , 4:30 PM 
//////////////////////////////////////////////////////////////////////////////////////////

/*****************************************************************************************
Name:		IsValidEmail
Purpose:	Checks whether a string represents a valid email format 
			like someone@domainname.com e.g. John@microsoft.com
Arguments:	str - The string to check for
Returns:	True if the string is in a valid email format, false otherwise
*****************************************************************************************/
function IsValidEmail(str)
{
	if (str.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
	{
		return true;
	}
	else
	{
		alert("Email is not in a valid format.");
		return false;
	}
	return (true);
}

/*****************************************************************************************
Name:		isURL
Purpose:	Checks whether a string represents a valid URL format 
			like someone@domainname.com e.g. John@microsoft.com
Arguments:	str - The string to check for
Returns:	True if the string is in a valid email format, false otherwise
*****************************************************************************************/

function isURL(urlStr)
{
	if(urlStr=="")
		return true;
	if (urlStr.indexOf(" ")!=-1){
		alert("Spaces are not allowed in a URL");
		return false;
	}
	if(urlStr==""||urlStr==null){
		return false;
	}
	urlStr=urlStr.toLowerCase();
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var atom=validChars + '+';
	var urlPat=/^http:\/\/(\w*)\.([\-\+a-z0-9]*)\.(\w*)/;
	var matchArray=urlStr.match(urlPat);
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	if (matchArray==null){
		alert("The URL seems incorrect \ncheck it begins with http.");
		return false;
	}
	var user=matchArray[2];
	var domain=matchArray[3];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("This domain contains invalid characters.");
			return false;
		}
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("This domain name contains invalid characters.");
			return false;
		}
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			alert("The domain name does not seem to be valid.");
			return false;
		}
	}
	if (domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	return true;
}

/*****************************************************************************************
Name:		Trim
Purpose:	Removes the leading and trailing spaces from a string
Arguments:	str - The string to be trimmed
Returns:	The string with leading and trailing spaces removed
*****************************************************************************************/
function Trim(value,type)
{
	var s,l
	s=value   // value of control
	t=type    // type is either of "both", "left", "right". Not giving any second parameter
			  // will lead to both trimming.
	l=s.length
	if(t==null || t=="both" || t=="left")
	while(s.substr(0,1)==" ")
	{
		s=s.substr(1,l-1)
		l=l-1
	}
	if(t==null || t=="both" || t=="right")
	while(s.substr(l-1,1)==" ")
	{
		s=s.substr(0,l-1)
		l=l-1
	}
	return s
}

/*****************************************************************************************
Name:		DateCompare
Purpose:	Compares two dates and returns the result 
Arguments:	dd,mm,yyyy - day,month,year for date1
 			dd1,mm1,yyyy1 - day,month,year for date2
Returns:	1 if date1 > date2, 0 if date1 = date2 and -1 if date1 < date2
*****************************************************************************************/
function DateCompare(dd,mm,yyyy,dd1,mm1,yyyy1)
{
	var dt = new Date();
	
	dt.setMonth(mm-1);
	dt.setDate(dd);
	dt.setFullYear(yyyy);
	
	var dt1 = new Date();
	
	dt1.setMonth(mm1-1);
	dt1.setDate(dd1);
	dt1.setFullYear(yyyy1);

	//alert("dt="+dt);
	//alert("dt1="+dt1);
	
	if(dt>dt1)	
		return 1;
	else if(dt<dt1)
		return -1;
	else 
		return 0;
}
/*****************************************************************************************
Name:		DateCompare
Purpose:	Compares two dates when those are send as dd/mm/yyyy
Arguments:	frmDate - dd/mm/yyyy , toDate - dd/mm/yyyy
Returns:	1 if frmDate > toDate, 0 if frmDate = toDate and -1 if frmDate < toDate
*****************************************************************************************/
function DateCompareDDMMYYYY(frmDate,toDate)
{
	frmDate = Trim(frmDate);
	toDate = Trim(toDate);
	
	var arfrDate = frmDate.split("/")		
	// Set individual dd, mm and yy/yyyy from date
	var dd = arfrDate[0];
	var mm = arfrDate[1];
	var yyyy = arfrDate[2];
		
	var artoDate = toDate.split("/")		
	// Set individual dd, mm and yy/yyyy to date
	var dd1 = artoDate[0];
	var mm1 = artoDate[1];
	var yyyy1 = artoDate[2];
	
	var dt = new Date();
	
	dt.setMonth(mm-1);
	dt.setDate(dd);
	dt.setFullYear(yyyy);
	
	var dt1 = new Date();
	
	dt1.setMonth(mm1-1);
	dt1.setDate(dd1);
	dt1.setFullYear(yyyy1);

	//alert("dt="+dt);
	//alert("dt1="+dt1);
	
	if(dt > dt1)	
		return 1;
	else if(dt < dt1)
		return -1;
	else 
		return 0;
}

/*****************************************************************************************
Name:		DOW
Purpose:	Returns the day of week, given a date 
Arguments:	dd,mm,yyyy - day,month,year for date
Returns:	The week day name in the format Sunday/Monday etc.
*****************************************************************************************/
function DOW(dd, mm, yyyy)
{
	var tmpdate   = creadate(yyyy,mm,dd); 
	var dow       = tmpdate.getDay(); 
	var wday      = new Array(7);
		wday[0] = 'Sunday';
		wday[1] = 'Monday';
		wday[2] = 'Tuesday';
		wday[3] = 'Wednesday';
		wday[4] = 'Thursday';
		wday[5] = 'Friday';
		wday[6] = 'Saturday';
	return (wday[dow]);}

/*****************************************************************************************
Name:		DateDiff
Purpose:	Returns the number of days between two dates 
Arguments:	fromdd,frommm,fromyyyy - day,month,year for date1
			todd,tomm,toyyyy - day,month,year for date2
Returns:	Number of days
*****************************************************************************************/
function DateDiff(fromdd, frommm, fromyyyy, todd, tomm, toyyyy)
{
	var fromdate = new Date(fromyyyy,frommm,fromdd,00,00,00,001); 
	var todate   = new Date(toyyyy,tomm,todd,00,00,00,001);
	var msPerDay = 24 * 60 * 60 * 1000 ;
	var daysleft = (todate.getTime() - fromdate.getTime())/msPerDay ;
	daysleft = Math.round(daysleft);
	return (daysleft);
}

/*****************************************************************************************
Name:		CreateDate
Purpose:	Returns a valid date given the day, month and year
Arguments:	yyyy,mm,dd - year,month,day for date
Returns:	The valid date constructed from the arguments or the default initialized date
			if invalid arguments are passed
*****************************************************************************************/
function CreateDate(yyyy, mm, dd)
{
	var tmpdt = new Date(0,1,1);
	if (!isValidDate(mm + '-' + dd + '-' + yyyy))
	{
		return tmpdt;
	}
	tmpdt.setYear(yyyy);
	tmpdt.setMonth(mm-1);
	tmpdt.setDate(dd);
	return (tmpdt);
 }
 
 
 

/*****************************************************************************************
Name:		IsEmpty
Purpose:	Checks whether a string is empty 
Arguments:	str - The string to check for
Returns:	True if the string is empty, false otherwise
*****************************************************************************************/
function IsEmpty(str)
{
	return (str.length == 0);
}
/*****************************************************************************************
Name:		IsNumeric
Purpose:	Checks whether it is a numeric value 
Arguments:	str - The string to check for
Returns:	True if the value is numeric, false otherwise
*****************************************************************************************/
function IsNumeric(str)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < str.length && IsNumber == true; i++) 
   { 
      Char = str.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
          IsNumber = false;
        
   }
   return IsNumber;
}

/*****************************************************************************************
Name:		Round
Purpose:	Rounds the number to the nearest integer
Arguments:	number - The number to round, decimalplaces - number of decimal places to round
Returns:	The rounded integer
*****************************************************************************************/
function Round(number, decimalplaces)
{
	var roundedoff = Math.round(number, decimalplaces);
	return (roundedoff);
}
   
/*****************************************************************************************
Name:		IsNumeric
Purpose:	Checks whether the argument is of number type
Arguments:	str - The string to check for, allowdecimal - whether or not to consider
			decimal places
Returns:	True if the argument is a number, false otherwise
*****************************************************************************************/
function IsNumeric(str, allowdecimal)
{
	if (str.length == 0)
	{return false;}
	var numstr = "0123456789";
	if (allowdecimal)
	{
		numstr += ".";
		if(str.lastIndexOf(".")!=str.indexOf("."))
			return false;
	}
	for (_j = 0; _j < str.length; _j++)
	{
		if (numstr.indexOf(str.charAt(_j)) == -1)
		{
			return (false);
		}
	}
	

   return true;
}

/*****************************************************************************************
Name:		IsDate
Purpose:	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.
Arguments:	dd,mm,yyyy - day,month,year for date, errmsg - the error message to show
Returns:	True if a valid date, false if not.
*****************************************************************************************/
function isDate(dateStr, msg) {

  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
  var matchArray = dateStr.match(datePat); // is format OK?

  if (matchArray == null) {
    alert("Please enter date as either dd/mm/yyyy or dd-mm-yyyy for "+msg+".");
    return false;	
  }

  // parse date into variables
  day = matchArray[1];
  month = matchArray[3];
  year = matchArray[5];

  if (month < 1 || month > 12) { // check month range
    alert(msg+" - Month must be between 1 and 12.");
    return false;
  }

  if (day < 1 || day > 31) {
    alert(msg+" - Day must be between 1 and 31.");
    return false;
  }

  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    alert(msg+" - 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(msg+" - February " + year + " doesn't have " + day + " days!");
      return false;
    }
  }
  return true;  // date is valid
}

/*****************************************************************************************
Name:		CharLimit
Purpose:	Checks whether the fields length is within a maximum allowed limit
Arguments:	field - The input field to check for, maxlimit - The maximum allowed value for
			this field, alertuser - whether or not to show msgbox
Returns:	True if the fields length is within the maxlimit, false otherwise
*****************************************************************************************/
function CharLimit(field, str, maxlimit, alertuser) 
{
if (field.value.length > maxlimit)
   {if (alertuser)
	{
		alert("You are limited to " + maxlimit + " characters for " + str + ".");
	}
    return false;
	}
else
	{
	return true;
	}
}
   
/*****************************************************************************************
Name:		IsContainSpaces
Purpose:	Checks whether a string contain inbetween spaces
Arguments:	str - The string to check for
Returns:	True if the string contains spaces, false otherwise
*****************************************************************************************/
function IsContainSpaces(str)
{
	i=0
	stat = true
	while(i < str.value.length && stat)   
	{
	if (str.value.charAt(i)!=' ')
	{
		stat=false
	}
	i++
	} 
	return stat
}

/*****************************************************************************************
Name:		IsEmptyField
Purpose:	Checks whether an HTML input field is empty or not
Arguments:	str - The string to be used in displaying message, fld - The field to check for
Returns:	True if the field is empty, false otherwise
*****************************************************************************************/
function IsEmptyField(str,fld)
{
	if (Trim(eval(fld).value,'')=="")
	{
		alert(str +" cannot be blank");
		eval(fld).focus();
		return false;
	}
	else
	{
		return true;
	}
}

/*****************************************************************************************
Name:		IsComboItemSelected
Purpose:	Checks whether an entry is selected in a combobox
Arguments:	str - The string to be used in displaying message, fld - The field to check for
Returns:	True if an entry is selected in the combobox, false otherwise
*****************************************************************************************/
function checkCombo(str,fld)
{
	if (eval(fld).selectedIndex==0)
	{
		alert("Please select a value for " + str);
		eval(fld).focus();
		return false;
	}
	else
	{
		return true;
	}
}

/*****************************************************************************************
Name:		IsSpecialChar
Purpose:	Checks whether there are any special characters in the field
Arguments:	str - The string to be used in displaying message, fld - The field to check for
Returns:	True if there are no special characters, false otherwise
*****************************************************************************************/
function IsSpecialChar(str,fld)
{
	var pattern =/\t|\n/;
	var fldval=eval(fld).value;
	if(fldval.search(pattern)>-1)
	{
		alert("Special characters like ENTER, etc. not allowed in "+ str +".\nPlease remove those characters.");
		eval(fld).focus();
		return true;
	}
	else
	{
		return false;
	}
}

/*****************************************************************************************
Name:		IsNull
Purpose:	Check whether a value is null
Arguments:	val - The string to check for
Returns:	True if value is null
*****************************************************************************************/
function IsNull(val)
{
	return(val==null);
}

/*****************************************************************************************
Name:		IsArray
Purpose:	Check whether an object is an array
Arguments:	obj - The object to be checked for
Returns:	True if the object is an array, else false
*****************************************************************************************/
function IsArray(obj)
{
	return(typeof(obj.length)=="undefined")?false:true;
}

/*****************************************************************************************
Name:		IsDigit
Purpose:	Check whether a value is a one character digit
Arguments:	num - The number to be checked for
Returns:	True if value is a 1-character digit
*****************************************************************************************/
function IsDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
	}

/*****************************************************************************************
Name:		SetNullIfBlank
Purpose:	Sets a form field to "" if it IsNull()
Arguments:	obj - The object to be set
Returns:	Nothing
*****************************************************************************************/
function SetNullIfBlank(obj)
{
	if(isNull(obj.value))
	{
		obj.value="";
	}
}

/*****************************************************************************************
Name:			Right
Purpose:		Return n characters from the right side of the string
Arguments:		str - the string we are RIGHTing,
				n - the number of characters we want to return	
Returns:		n characters from the right side of the string
*/
function Right(str, n)
{
		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);
		}
}
/*****************************************************************************************
Name:			isProper
Purpose:		Checks Whether a Paricular string contains any special character
Arguments:		The Field Value
Returns:		if found then false, else true
*******************************************************************************************/
function isProper(string) {

   if (!string) return false;
   var iChars = "*|,\":~`\'&";

   for (var i = 0; i < string.length; i++) {
      if (iChars.indexOf(string.charAt(i)) != -1)
         return false;
   }
   return true;
} 

/*****************************************************************************************
Name:			replaceSpecialChar
Purpose:		replaces some special characters 
Arguments:		The Field Value
Returns:		returns the string replacing special characters
*******************************************************************************************/
function replaceSpecialChar(string) {

	if (!string) return false;
	while((string.indexOf("|")!=-1) || (string.indexOf("'")!=-1) || (string.indexOf("\"")!=-1) || (string.indexOf("\\")!=-1))
	{
		string=string.replace(/\\/,"")
		string=string.replace(/'/,"")
		string=string.replace(/\|/,"")
		string=string.replace(/\"/,"")
	}
	return(string)
} 
/*****************************************************************************************
Name:			isFieldBlank
Purpose:		Checks Whether a Paricular control Is blank Or Not
Arguments:		theField- The Field Value
			S - Mesage To Be Shown In Alert
Returns:		Alert In case the function is false
*/

function isFieldBlank(theField,S)
 {	
  var i = theField.length ;
  var counter = 0;
  for ( var j = 0 ; j < theField.length ; j++ )
  {
   var ch=theField.substring( j, j + 1 );
   if ( ch == " " )  counter += 1;
  }
if ( counter == i )
 {
 alert("Please Fill in the " + S);
 return true ;
 }
else
 {
 return false ;
 }
}


function ItemFormat(ControlValue,RequiredLength,DotRequired)
{
//This function is mainly for alignment in listbox.
   CVal = ControlValue //Value of Control
   CLen = ControlValue.length
   RLen = RequiredLength //Required Full Length 
   DReq = DotRequired //DReq=1 for Adding Dots at the End of Larger Control Value
	if(CLen<=RLen)
	{
	CLen=RLen-CLen
	for(j=0;j<CLen;j++)
	{
	CVal=CVal+" "
	}
	}
	else
	if(DReq==1)
	{
	CVal=CVal.substr(0,RLen-3)
	CVal=CVal+"..."
	}
   return CVal
}


 //Use =>  onKeyPress="filterInput(this)" allow="/[A-Z0-9]/" on the control where u want to implement
 function filterInput(e) 
  {
	 // Get the regular expression to test against for this particular object
   	 regAllow = (e)?eval(e.allow):eval(event.srcElement.allow);

   	 // Check for an allowed character, if not found, cancel the keypress's event bubbling
   	 if (!String.fromCharCode(event.keyCode).match(regAllow)) event.returnValue=false;
  }
  
/*****************************************************************************************
Name:			ConvertToMMDDYYYY
Purpose:		Converts a valid date in dd/mm/yyyy format to mm/dd/yyyy
				format
Arguments:		dtDDMMYYYY - Must be a valid date in the format
				dd/mm/yyyy
Returns:		date in mm/dd/yyyy format. In case of invalid date wrong value
				will be returned
*/
function ConvertToMMDDYYYY(dtDDMMYYYY)
{
 	var arrDate = dtDDMMYYYY.split("/");
	var dd = arrDate[0];
	var mm = arrDate[1];
	var yyyy = arrDate[2];
	
	var mmddyyyy = mm + '/' + dd + '/' + yyyy;
	return mmddyyyy;
 }
 
/*****************************************************************************************
Name:			ConvertToDDMMYYYY
Purpose:		Converts a valid date in mm/dd/yyyy format to dd/mm/yyyy
				format
Arguments:		dtMMDDYYYY - Must be a valid date in the format
				dd/mm/yyyy
Returns:		date in mm/dd/yyyy format. In case of invalid date wrong value
				will be returned
*/
function ConvertToDDMMYYYY(dtMMDDYYYY)
{
 	var arrDate = dtMMDDYYYY.split("/");
	var dd = arrDate[1];
	var mm = arrDate[0];
	var yyyy = arrDate[2];
	
	var ddmmyyyy = dd + '/' + mm + '/' + yyyy;
	return ddmmyyyy;
 }
 
 
/*****************************************************************************************
Name		:		disableRightClick
Purpose		:		To Disable the Right-Click on the Browser Window
Created By	:		Subhajit Datta Roy		
Arguments	:		Event Object , ByDefault it takes Right-Click
Returns		:		Message "Right click disabled"	 
*******************************************************************************************/ 
function disableRightClick(e)
{
	  var message = "Right click disabled";	  
	  if(!document.rightClickDisabled) // initialize
	  {
		if(document.layers) 
		{
		  document.captureEvents(Event.MOUSEDOWN);
		  document.onmousedown = disableRightClick;
		}
		else document.oncontextmenu = disableRightClick;
		return document.rightClickDisabled = true;
	  }
	  if(document.layers || (document.getElementById && !document.all))
	  {
		if (e.which==2||e.which==3)
		{
		  alert(message);
		  return false;
		}
	  }
	  else
	  {
		alert(message);
		return false;
	  }
}
/*****************************************************************************************
Name		:		setStatusBar
Purpose		:		To show Message on the Status Bar
Created By	:		Subhajit Datta Roy		
Arguments	:		msgStr - the message taht will be displayed on the Status Bar
Returns		:		Status Bar Message 	 
*******************************************************************************************/ 
function setStatusBar(msgStr) { self.status = msgStr; }


function wrtext(txt,charNo)
{
  var charPerLine = charNo;
  for(var i=0; i < txt.length;)
  {
	 for(var j=0; j<charPerLine;j++,i++)
	 {
		document.write(txt.charAt(i));
	 }
	 document.write("\n");
  }
}