/*
email : 
isblank : 
isdate : 
noquotes : 
objtrim : 
strtrim : 
*/


/* Function to check valid email : requires strim as parameter, not the object
Last Modify: 30/05/01
*/
function email(strval)
{

 if (typeof(strval) == "object")
 {
    objtrim(strval);
	emailStr = strval.value;
 }
 else
 {
    emailStr = strtrim(strval);
 }

 
 /* Whether to verify email ends in two-letter country or well-known TLD.  1 means check it, 0 means don't. */
 var checkTLD=1;

 /* List of known TLDs that email must end with. */
 var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum|shop)$/;

 /* Pattern used to check if email fits 'user@domain' format.Also is to separate the username from the domain */
 var emailPat=/^(.+)@(.+)$/;

 /* Pattern for matching all special chars.Not allowedchars includes ( ) < > @ , ; : \ " . [ ] */
 var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]'";

 /* Range of chars allowed in a user/domain name.It really states which chars aren't allowed.*/
 var validChars="\[^\\s" + specialChars + "\]";

 /* Pattern that applies if the "user" is a quoted string (in which case, anything goes).  E.g. "jiminy cricket"@disney.com is a legal e-mail address. */
 var quotedUser="(\"[^\"]*\")";

 /* Domains that are IP addresses, rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
 e-mail address,square brackets reqred. */
 var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

 /* The following string represents an atom (basically a series of non-special characters.) */
 var atom=validChars + '+';

 /* Represents one word in the typical username. Eg, in john.doe@somewhere.com, john & doe are words.
 I.e., a word is either an atom or quoted string. */
 var word="(" + atom + "|" + quotedUser + ")";

 // Pattern describes the structure of the user
 var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

 /* Pattern describes structure of normal symbolic domain, as opposed to ipDomainPat, shown above. */
 var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

 /* Finally, check if the email is valid. Begin with coarse pattern to simply break up user@domain into diff pieces easy to analyze. */
 var matchArray=emailStr.match(emailPat);

 if (matchArray==null) 
 {
    /* Too many/few @'s or something; ie, this email doesn't even fit the general mould of a valid mail addr. */
    // alert("Email address seems incorrect (check @ and .'s)");
    return false;
 }
 
 var user=matchArray[1];
 var domain=matchArray[2];

 // Start by checking that only basic ASCII characters are in the strings (0-127).
 for (i=0; i<user.length; i++) 
 {
     if (user.charCodeAt(i) > 127) 
	 {
	    // alert("Ths username 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;
	}
 }

 // If valid "user"
 if (user.match(userPat) == null) 
 { 
    // alert("The username doesn't seem to be valid.");
	return false;
 }

 /* If email is at an IP addr (not symbolic hostname) make sure valid IP */
 var IPArray=domain.match(ipDomainPat);
 if (IPArray!=null) 
 {// this is an IP address
    for (var i=1;i<=4;i++) 
	{
	   if (IPArray[i]>255) 
	   {
	      // alert("Destination IP address is invalid!");
		  return false;
	   }
	}
	return true;
 }

 // Domain is symbolic name.  Check if it's valid.
 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 Dom name valid, make sure it ends in a known TLD or a 2-letter country name, and that there's a hostname preceding the TLD. */
 if (checkTLD && 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;
 }

 // Make sure there's a host name preceding the domain.
 if (len<2) 
 {
    // alert("This address is missing a hostname!");
	return false;
 }

 // If we've gotten this far, everything's valid!
 return true;
}


/* Last Update: 20/05/01   */

function isdate(val) 
{

 if (typeof(val) == "object")
 {
    objtrim(val);
    objName = val;
 }
 else
 {
    objName = strtrim(val);
 }

 var datefield = objName;
 if (chkdate(objName) == false) 
 {
    datefield.select();
	alert("That date is invalid. Try again and please ensure that it is in 'dd/mm/yy' format");
	datefield.focus();
	return false;
 }
 else 
 {
    return true;
 }
}

function chkdate(objName) 
{
// var strDatestyle = "US"; //United States date style
 var strDatestyle = "EU";  //European date style
 var strDate;
 var strDateArray;
 var strDay;
 var strMonth;
 var strYear;
 var intday;
 var intMonth;
 var intYear;
 var booFound = false;
 var datefield = objName;
 var strSeparatorArray = new Array("-"," ","/",".");
 var intElementNr;
 var err = 0;
 var strMonthArray = new Array(12);

 // Create and array of months with their names
 strMonthArray[0] = "Jan";
 strMonthArray[1] = "Feb";
 strMonthArray[2] = "Mar";
 strMonthArray[3] = "Apr";
 strMonthArray[4] = "May";
 strMonthArray[5] = "Jun";
 strMonthArray[6] = "Jul";
 strMonthArray[7] = "Aug";
 strMonthArray[8] = "Sep";
 strMonthArray[9] = "Oct";
 strMonthArray[10] = "Nov";
 strMonthArray[11] = "Dec";
 strDate = datefield.value;
 
 // Nulls are allowed
 if (strDate.length < 1) 
 {    return true; }
 
 for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) 
 {
    // Separate dd & mm & yy by splitting on common delimiters (- / . & space)
	if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) 
	{  strDateArray = strDate.split(strSeparatorArray[intElementNr]);

	   // If componentd are not enough
	   if (strDateArray.length != 3) 
	   {
	      err = 1;
		  return false;
	   }
       else 
	   {
	      // Separate date components and put them into separate vars for day, month and year		  
		  strDay = strDateArray[0];
		  strMonth = strDateArray[1];
		  strYear = strDateArray[2];
       }
	   booFound = true;
	}
 }
 
 if (booFound == false) 
 {
    if (strDate.length>5) 
	{
	   strDay = strDate.substr(0, 2);
	   strMonth = strDate.substr(2, 2);
	   strYear = strDate.substr(4);
    }
 }
 
 if (strYear.length == 2) 
 {  strYear = '20' + strYear; }

 // US style
 if (strDatestyle == "US") 
 {
    strTemp = strDay;
	strDay = strMonth;
	strMonth = strTemp;
 }
 
 intday = parseInt(strDay, 10);
 
 if (isNaN(intday)) 
 {
    err = 2;
	return false;
 }

 intMonth = parseInt(strMonth, 10);
 if (isNaN(intMonth)) 
 {
    for (i = 0;i<12;i++) 
	{
	   if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) 
	   {
	      intMonth = i+1;
		  strMonth = strMonthArray[i];
		  i = 12;
       }
    }
    
	if (isNaN(intMonth)) 
	{
	   err = 3;
	   return false;
    }
 }

 intYear = parseInt(strYear, 10);
 if (isNaN(intYear)) 
 {
    err = 4;
	return false;
 }

 // Invalid month number 
 if (intMonth>12 || intMonth<1) 
 {
    err = 5;
	return false;
 }

 // These months are allowed 31 days, invalidate any entries greater that 31 and lesser than 1
 if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) 
 {
    err = 6;
	return false;
 }

 // These months are allowed 30 days, invalidate any entries greater that 30 and lesser than 1
 if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) 
 {
    err = 7;
	return false;
 }

 // Check days for feb now
 if (intMonth == 2) 
 {
    if (intday < 1) 
	{
	   err = 8;
	   return false;
    }
	
	// For leap yrs, feb gets 29 days
	if (LeapYear(intYear) == true) 
	{
	   if (intday > 29) 
	   {
	      err = 9;
		  return false;
	   }
	 }
	 else 
	 {
	    if (intday > 28) 
		{
		   err = 10;
		   return false;
		}
	 }
 }
 
// if (strDatestyle == "US") 
// {  datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear; }
// else 
// {  datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear; }

 return true;
}

// Function that checks if the year is a leap year
function LeapYear(intYear) 
{
   if (intYear % 100 == 0) 
   {
      if (intYear % 400 == 0) { return true; }
   }
   else 
   {
      if ((intYear % 4) == 0) { return true; }
   }
 return false;
}

// func isblank()parameter is string to be compared. returns true if it does not contain any 
// non-whitespace character
function isblank(strval)
{
   if (typeof(strval) == "object")
   {  objtrim(strval);
	  str = strval.value;
   }
   else
   {  str = strtrim(strval);   }

   var len = str.length;
   for (var i = 0; i < len; i++)
   {
      if (str.charAt(i) != " ")
      {
	     return false;				// If the is any non-space character, isblank() returns false
      }
   }
   return true;
}

// Alltrim function meant only for string value. Returns trimmed value
// Last Modify : 28/05/01
function strtrim(val)
{
   while('' + val.charAt(0)==' ')
   {
      val = val.substring(1,val.length);
   }

   while('' + val.charAt(val.length-1)==' ')
   {
      val = val.substring(0,val.length-1)
   }

   return val;
}

// Alltrim func when object is passed. 
// last Modify : 28/05/01
function objtrim(box)
{
   while('' + box.value.charAt(0)==' ')
   {
      box.value = box.value.substring(1,box.value.length);
   }

   while(''+box.value.charAt(box.value.length-1)==' ')
   {
      box.value = box.value.substring(0,box.value.length-1)
   }

}

// Function to return false if there are any single quotes in 
function noquotes(str)
{
   for (var i=0; i < str.length ; i++ )
   {
      if (str.charAt(i) == "'")
      {
	     return false;				// If the is any non-space character, isblank() returns false
      }
   }
   return true;
}

//04/06/02 - ES(4)
function isdropdate(day,mon,year)
{
	var dtcorrect;
	dtcorrect = true;
	

	if ((year % 4) == 0)
	{
		if (mon == 'Feb')
		{
			if (day > 29)
			{
				dtcorrect = false;
			}
		}
	}
	else
	{
		if (mon == 'Feb')
		{
			if (day > 28)
			{
				dtcorrect = false;
			}
		}
	}
	switch (mon)
	{
		case 'Apr':
		case 'Jun':
		case 'May':
		case 'Sep':
		case 'Nov': if (day > 30)
					{
						dtcorrect = false;
					}
	}
	return dtcorrect;
}



function addSpace(argvalue, numlength) {
/*
Description
==============
When you want to align the value of the form text box, you can use this function. 

Examples
========
The following returns "    123.45".
addSpace("123.45", 10);
addSpace("123.45");

Code
====
*/

  if (! numlength > 0)
    numlength = 10;

  if (argvalue.length < numlength) {
    for(var i = argvalue.length; i < numlength; i++)
      argvalue = " " + argvalue;
  }

  return argvalue;

}

//=========================================================================

function customSplit(strvalue, separator, arrayName) {

/*
Syntax
======
customSplit(strValue, separator, strArrayName)
strValue is the string to be splited with separator as the delimeter. After spliting, array of strings are stored in new "Array" object, strArrayName. 

Description
===========
Since some of the browsers does not support latest version of javascript, which has split() function. "customSplit" function can be used then.
This function will return the length of the array created.


Examples
========
var strvalue = "abc##123##zzz##$$$";
var returnArraySize = customSplit(strvalue, "##", "NewArray");
The above will create the following:
NewArray[0] has value "abc"
NewArray[1] has value "123"
NewArray[2] has value "zzz"
NewArray[3] has value "$$$"
returnArraySize      has value "4"

Code
====
*/
  var n = 0;

  if (separator.length != 0) {
    while (strvalue.indexOf(separator) != -1) {
      eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));");
      strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length,
          strvalue.length+1);
      n++;
    }
    eval("arr" + n + " = strvalue;");
    arraySize = n+1;
  }
  else {
    for (var x = 0; x < strvalue.length; x++) {
      eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";");
      n++;
    }
    arraySize = n;
  }

  eval(arrayName + " = new makeArray(arraySize);");

  for (var i = 0; i < arraySize; i++)
    eval(arrayName + "[" + i + "] = arr" + i + ";");

  return arraySize;
}

//==============================================================

function DeleteCookie(cookiename) {

/*
Syntax
======
DeleteCookie(cookieName)
cookieName is the cookie that you want to delete.


Description
===========
Examples
=======
Code
====
*/

  var exp = new Date();

  exp.setTime(exp.getTime() - 1);
  var cookieVal = getCookie(cookiename);
  if (cookieVal != null)
    document.cookie = name + "=" + cookieVal + "; expires=" + exp.toGMTString();

  return;

}

//==========================================================================

function formatDecimal(argvalue, addzero, decimaln) {

/*
Syntax
======
formatDecimal(number, boolean, decimal)
number is the floating point number which will be formatted.

boolean is used to decide whether add "0" at the end of the floating point number or not.

decimal is how many decimal point you wnat. (Default is 2)


Description
===========
This function will print the floating point number passed in with the decimal point that users need.

Examples
========
formatDecimal("123.2333", true, 2);	will return "123.23".
formatDecimal("123", true, 2);		will return "123.00".
formatDecimal("123", false, 2);		will return "123".
formatDecimal("123.2", true, 2);	will return "123.20".
formatDecimal("123.2", false, 2);	will return "123.2".
formatDecimal("123.456", true, 2);	will return "123.46".
formatDecimal(".235", true, 2);		will return "0.24".
formatDecimal("0.9999", true, 2);	will return "1.00".
formatDecimal("0.9999", false, 2);	will return "1".


Code
====
*/

  var numOfDecimal = (decimaln == null) ? 2 : decimaln;
  var number = 1;

  number = Math.pow(10, numOfDecimal);

  argvalue = Math.round(parseFloat(argvalue) * number) / number;
  // If you're using IE3.x, you will get error with the following line.
  // argvalue = argvalue.toString();
  // It works fine in IE4.
  argvalue = "" + argvalue;

  if (argvalue.indexOf(".") == 0)
    argvalue = "0" + argvalue;

  if (addzero == true) {
    if (argvalue.indexOf(".") == -1)
      argvalue = argvalue + ".";

    while ((argvalue.indexOf(".") + 1) > (argvalue.length - numOfDecimal))
      argvalue = argvalue + "0";
  }

  return argvalue;
}


//=========================================================================
/*
formatValue function
====================
Print a number according to the format specified. Used for currency format.

Syntax
======
formatValue(argvalue, format)
argvalue is the number which will be formatted.

format is the format of the result.


Description
===========
The number passed in will be formatted according to the format specified by the user. This function is written for formatting a currency number.
And formatDecimal function is needed.


Examples
========
formatValue(1223.434, "$##,###.##")		will return "$1,223.43"
formatValue(1223.43, "$##,###.##")		will return "$1,223.43"
formatValue(1223., "$##,###.##")		will return "$1,223.00"
formatValue(1223, "$##,###.##")		will return "$1,223.00"
formatValue(23., "$##,###.##")			will return "$23.00"
formatValue(23.3, "$##,###.##")		will return "$23.30"
formatValue(124343423.3, "$###,###,###.##")	will return "$124,343,423.30"

Code
====
*/
function formatValue(argvalue, format) {
  var numOfDecimal = 0;
  if (format.indexOf(".") != -1) {
    numOfDecimal = format.substring(format.indexOf(".") + 1, format.length).length;
  }
  argvalue = formatDecimal(argvalue, true, numOfDecimal);

  argvalueBeforeDot = argvalue.substring(0, argvalue.indexOf("."));
  retValue = argvalue.substring(argvalue.indexOf("."), argvalue.length);

  strBeforeDot = format.substring(0, format.indexOf("."));

  for (var n = strBeforeDot.length - 1; n >= 0; n--) {
    oneformatchar = strBeforeDot.substring(n, n + 1);
    if (oneformatchar == "#") {
      if (argvalueBeforeDot.length > 0) {
        argvalueonechar = argvalueBeforeDot.substring(argvalueBeforeDot.length - 1, argvalueBeforeDot.length);
        retValue = argvalueonechar + retValue;
        argvalueBeforeDot = argvalueBeforeDot.substring(0, argvalueBeforeDot.length - 1);
      }
    }
    else {
      if (argvalueBeforeDot.length > 0 || n == 0)
        retValue = oneformatchar + retValue;
    }
  }

  return retValue;
}

//===========================================================================
/*
GetCookie function
==================
Get the value of a cookie.

Syntax
======
GetCookie(CookieName)
CookieName is the cookie whose value that you want to get.


Description
===========
If the cookie specified doesn't exist, "null" will be returned.

Examples
========
If the document.cookie contains:
USER_ID=abc
USER_GP=

// variable "userid" has value "abc".
var userid = GetCookie("USER_ID");
// variable "usergp" has value "".
var usergp = GetCookie("USER_GP");
// variable "userpw" has null value.
var userpw = GetCookie("USER_PW");

Code
====
*/
function GetCookie(name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while (i < clen) {
    var j = i + alen;

    if (document.cookie.substring(i, j) == arg)
      return GetCookieVal(j);

    i = document.cookie.indexOf(" ", i) + 1;

    if (i == 0) 
      break; 
  }

  return null;
}

function GetCookieVal(offset) {
  var endstr = document.cookie.indexOf(";", offset);

  if (("" + endstr) == "" || endstr == -1)
    endstr = document.cookie.length;

  return unescape(document.cookie.substring(offset, endstr));
}


//==========================================================================

/*
isURL function
==============
Determine an argument if it is a URL.

Syntax
======
isURL(testValue)
testValue is the value that you want to check.


Description
===========

Examples
========
The followings will return "true".
isURL("http://some.host");
isURL("http://some.host/");
isURL("http://some.host/dir");
isURL("http://some.host/dir/");
isURL("http://some.host/dir/htmlfile");
isURL("http://some.host:123");
isURL("http://some.host:123/");

The followings will return "false".
isURL("http://.some.host/");
isURL("http://some.host./");
isURL("http://some.host:/");
isURL("http://some.host:.123/");
isURL("http://some.host:123./");
isURL("http://some.host:123./dir";
isURL("http://");
isURL("htp://");

Code
====
*/
function isURL(argvalue) {

  if (argvalue.indexOf(" ") != -1)
    return false;
  else if (argvalue.indexOf("http://") == -1)
    return false;
  else if (argvalue == "http://")
    return false;
  else if (argvalue.indexOf("http://") > 0)
    return false;

  argvalue = argvalue.substring(7, argvalue.length);
  if (argvalue.indexOf(".") == -1)
    return false;
  else if (argvalue.indexOf(".") == 0)
    return false;
  else if (argvalue.charAt(argvalue.length - 1) == ".")
    return false;

  if (argvalue.indexOf("/") != -1) {
    argvalue = argvalue.substring(0, argvalue.indexOf("/"));
    if (argvalue.charAt(argvalue.length - 1) == ".")
      return false;
  }

  if (argvalue.indexOf(":") != -1) {
    if (argvalue.indexOf(":") == (argvalue.length - 1))
      return false;
    else if (argvalue.charAt(argvalue.indexOf(":") + 1) == ".")
      return false;
    argvalue = argvalue.substring(0, argvalue.indexOf(":"));
    if (argvalue.charAt(argvalue.length - 1) == ".")
      return false;
  }

  return true;

}

//=====================================================================
/*
isW function
============
Determine an argument if it only contains "word" characters.

Syntax
======
isW(testValue)
testValue is the value that you want to check.


Description
===========
"Word" characters are alphanumeric plus "_".

Example
=======
The followings will return "true".
isW("abc123")
isW("ABC123")
isW("aBc_123")

The followings will return "false".
isW("abc 123")
isW("@#+=")
isW("! Abc")

Code
====
*/
function isW(argvalue) {
  var onechar = "";

  for (var n = 0; n < argvalue.length; n++) {
    onechar = argvalue.substring(n, n+1);
    if ((onechar < "0" || onechar > "9") && (onechar < "A" ||
      onechar > "Z") && (onechar < "a" || onechar > "z") &&
         (onechar != "_")) {
      return false;
    }
  }

  return true;

}

//========================================================================
/*
ltrim function
==============
Remove the leading space/s of an argument.

Syntax
======
ltrim(stringValue)
stringValue is the string which the leading space/s will be removed.


Description
===========

Examples
========
The following will return "abc ".
ltrim("  abc ")
The following will return "a b c  ".
ltrim("  a b c  ")

Code
====
*/
function ltrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ")
      break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}

//========================================================================
/*
ParseCookies function
=====================
Parse the cookies data and assign these data to "document.Cookie_cookie_name".

Syntax
======
ParseCookies()

Description
===========
The value of cookie, cookieName, is stored in "document.Cookie_cookieName.value".
There are few ways to save the cookie data, but I found that this is the way which works in both Netscape3.0 and Internet Explorer3.0.


Examples
========
If the server returns the following cookie:
  Set-Cookie: Cookie1=Value1; Cookie2=Value2
After you call the ParseCookies().
parseCookies();
"document.Cookie_Cookie1.value" will contains value "Value1";
"document.Cookie_Cookie1.name" will contains value "Cookie1";
"document.Cookie_Cookie2.value" will contains value "Value2";
"document.Cookie_Cookie2.name" will contains value "Cookie2";

Code
====
*/
function ParseCookies() {
  var cookie_string;
  var cookie_name;
  var cookie_value;
  var tmpcookie = document.cookie;
  var cookie_count = 0;

  while (tmpcookie.indexOf("; ") != -1) {
    cookie_string = tmpcookie.substring(0, tmpcookie.indexOf("; "));
    cookie_name = cookie_string.substring(0, cookie_string.indexOf("="));
    cookie_value = cookie_string.substring(cookie_string.indexOf("=") + 
        "=".length, cookie_string.length);
    eval("document.Cookie_" + cookie_name + 
	" = new Cookies(cookie_name, cookie_value);");

    tmpcookie = tmpcookie.substring(tmpcookie.indexOf("; ") + "; ".length, 
        tmpcookie.length);

    cookie_count++;
  }

  cookie_name = tmpcookie.substring(0, tmpcookie.indexOf("="));
  cookie_value = tmpcookie.substring(tmpcookie.indexOf("=") + "=".length, 
        tmpcookie.length);
  eval("document.Cookie_" + cookie_name + 
	" = new Cookies(cookie_name, cookie_value);");
  cookie_count++;
  
  return cookie_count;

}

function Cookies(argname, argvalue) {
  this.name = argname;
  this.value = unescape(argvalue);

  return this;

}

//=========================================================================
/*
replace function
================
Substitute a string X to a string Y in an argument.

Syntax
======
replace(stringValue, X, Y)
stringValue is the string which has all X will be substituted by Y.


Description
===========
This function will replace all the string X to string Y in the argument, it can not change the string X in certain place.

Examples
========
The following will return "abcABCdefgh".
replace("abc123defgh", "123", "ABC");

Code
====
*/
function replace(argvalue, x, y) {

  if ((x == y) || (parseInt(y.indexOf(x)) > -1)) {
    errmessage = "replace function error: \n";
    errmessage += "Second argument and third argument could be the same ";
    errmessage += "or third argument contains second argument.\n";
    errmessage += "This will create an infinite loop as it's replaced globally.";
    alert(errmessage);
    return false;
  }
    
  while (argvalue.indexOf(x) != -1) {
    var leading = argvalue.substring(0, argvalue.indexOf(x));
    var trailing = argvalue.substring(argvalue.indexOf(x) + x.length, 
	argvalue.length);
    argvalue = leading + y + trailing;
  }

  return argvalue;

}

//=====================================================================
/*
rtrim function
==============
Remove the trailing space/s of an argument.

Syntax
======
rtrim(stringValue)
stringValue is the string that you want to remove its trailing space/s.


Description
===========
Examples
========
The following will return "abc".
rtrim("abc   ")
The following will return "a b c".
rtrim("a b c   ")
The following will return "  abc".
rtrim("  abc  ")

Code
====
*/
function rtrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }

  return argvalue;
}

//=========================================================================
/*
SetCookie function
==================
Setting new cookie value.

Syntax
======
SetCookie(cookiename, cookievalue, expires, path, domain, secure)

Description
===========
To retrieve the cookie's value, try parseCookie function.
For more information about cookie, see Netscape's Cookie Specification at http://home.netscape.com/newsref/std/cookie_spec.html. 

Examples
========
SetCookie("Cookie1", "Value1", null, "/");
SetCookie("Cookie2", "Value2", new Date(), "/");
document.cookie will have value "Cookie1=Value1; Cookie2=Value2".

Code
====
*/
function SetCookie(cookiename, cookievalue) {
  var argv = SetCookie.arguments;
  var argc = SetCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = cookiename + "=" + escape(cookievalue) +
    ((expires == null) ? "" 	    : ("; expires=" + expires.toGMTString())) +
    ((path    == null) ? ""	    : ("; path="    + path                 )) +
    ((domain  == null) ? "" 	    : ("; domain="  + domain               )) +
    ((secure  == true) ? "; secure" : "");

  return;

}

//=========================================================================
/*
trim function
=============
Remove both the leading and the trailing space/s of an argument.

Syntax
======
trim(stringValue)
stringValue is the string which the leading and the trailing space/s will be removed.


Description
===========
When you use this function, make sure ltrim and rtrim are inside the same html file too.

Examples
========
The following will return "abc".
trim("  abc  ")
The following will return "a b c".
trim("  a b c  ")

Code
====
*/
function trim(argvalue) {
  var tmpstr = ltrim(argvalue);

  return rtrim(tmpstr);

}


