function  validateString( strValue ) {
 var objRegExp  =  /(^[a-zA-Z]+$)/; 
  return objRegExp.test(strValue);
}
function validateNumeric( field ) {
/******************************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.

PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
	 var objRegExp  =  /(^\d\d*\d*$)|(^\d\d*$)|(^\d\d*$)/; 
	
	//check for numeric characters 
	// return objRegExp.test(strValue);
	if(!objRegExp.test(field) || parseFloat(field) <= 0 || trimAll(field) == ""){
		   return 0;
	 }else{
			return 1;
	}
}
function parseCurrency(field){
	  var currency = /^\d*(?:\.\d{0,2})?$/;
	  
	  if(!currency.test(field) || parseInt(field) <= 0)
	  {
		   return 0;
	  }else{
	return 1;
  }
 }
function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid integer number.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
******************************************************************************/
  var objRegExp  = /(^-?\d\d*$)/;

	if(parseInt(strValue) <= 0){
		return false;
	}
  //check for integer characters
  return objRegExp.test(strValue);
}

function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
  blank (whitespace) characters.
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
   var strTemp = strValue;
   strTemp = trimAll(strTemp);
   if(strTemp.length > 0){
     return true;
   }  
   return false;
}
function popUp(URL,WIDTH,HEIGHT) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,"+WIDTH+","+HEIGHT+"');");
}
function validateEmail( strValue) {
  var objRegExp  = /^([a-z0-9])([a-z0-9_\-]*)([\.]{0,1}([a-z0-9_\-]*))@([a-z0-9_\-]+)([\.]{1})([a-z]{2,3}(\.[a-z]{2}){0,2})$/i;
    //check for valid email
    return objRegExp.test(strValue);
 }

function rightTrim( strValue ) {
/************************************************
DESCRIPTION: Trims trailing whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed.  
      
RETURNS:
   Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove trailing a whitespace characters
       strValue = strValue.replace(objRegExp, '$1');
    }
  return strValue;
}
function trim(pull_value)
{
   cleaned_value = pull_value.replace(/&nbsp;/g,'');
   cleaned_value = cleaned_value.replace(/^\s+|\s+$/, '');
   return cleaned_value;
}
function  validatename(strValue) {
 var objRegExp  =  /(^[a-zA-Z\ ]+$)/; 
  return objRegExp.test(strValue);
}
function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.
    
PARAMETERS:
   strValue - String to be trimmed
   
RETURNS:
   Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;
 
      if(objRegExp.test(strValue)) {
       //remove leading a whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/ 
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }
    
   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function validateCurrency( strValue)  {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid currency format. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp = /(^\$\d{1,3}(,\d{3})*\.\d{2}$)|(^\(\$\d{1,3}(,\d{3})*\.\d{2}\)$)/;

  return objRegExp.test( strValue );
}

function validateTime ( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid 12 hour time format. Seconds are optional.
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

REMARKS: Returns True for time formats such as:
  HH:MM or HH:MM:SS or HH:MM:SS.mmm (where the
  .mmm is milliseconds as used in SQL Server 
  datetime datatype.  Also, the .mmm portion will 
  accept 1 to 3 digits after the period)
*************************************************/
  var objRegExp = /^([1-9]|1[0-2]):[0-5]\d(:[0-5]\d(\.\d{1,3})?)?$/;

  return objRegExp.test( strValue );

}

function validateState (strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid state abbreviation. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/

var objRegExp = /^(AK|AL|AR|AZ|CA|CO|CT|DC|DE|FL|GA|HI|IA|ID|IL|IN|KS|KY|LA|MA|MD|ME|MI|MN|MO|MS|MT|NB|NC|ND|NH|NJ|NM|NV|NY|OH|OK|OR|PA|RI|SC|SD|TN|TX|UT|VA|VT|WA|WI|WV|WY)$/i; 
  return objRegExp.test(strValue);
}

function validateSSN( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains a 
  valid social security number. 
  
 PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp  = /^\d{3}\-\d{2}\-\d{4}$/;
 
  //check for valid SSN
  return objRegExp.test(strValue);

}



function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern. 
  Ex. (999) 999-9999 or (999)999-9999
  
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
*************************************************/
  var objRegExp  = /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/;
 
  //check for valid us phone with or without space between 
  //area code
  return objRegExp.test(strValue); 
}

function validateUSPhoneNumber( strValue ) {
	if(strValue == null)
		return false;
	if(strValue.length != 10){
		return false;
	}
	if(!validateInteger(strValue)){
		return false;
	}
	return true;
}

function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 or 99999-9999
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.

*************************************************/
var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
 
  //check for valid US Zipcode
  return objRegExp.test(strValue);
}

function validateUrl(strValue){ 
	var objRegExp;
	var returnvalue;

	objRegExp = /^([a-z0-9_\-\.]*)([a-z0-9_\-])$/;

	if(objRegExp.test(strValue) == true){

		var StringValue = strValue.substring(0,4);
		var strArr = strValue.split(".");
		var ArrLen = strArr.length;
		if((StringValue == "www." || StringValue == "WWW.") && ArrLen == 2){
		returnvalue = false;
		}else if(ArrLen < 2){
		objRegExp=/^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.|http:\/\/|https:\/\/){1}([\w]+)(.[\w]+){1,2}$/;

		returnvalue = objRegExp.test(strValue);
		}else{
		returnvalue = true;
		}
	}else{
		objRegExp=/^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.|http:\/\/|https:\/\/){1}([\w]+)(.[\w]+){1,2}$/;

		returnvalue = objRegExp.test(strValue);
		
	}

	return returnvalue;
} 
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;

}
function validateUSDate( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only 
    valid dates with 2 digit month, 2 digit day, 
    4 digit year. Date separator can be ., -, or /.
    Uses combination of regular expressions and 
    string parsing to validate date.
    Ex. mm/dd/yyyy or mm-dd-yyyy or mm.dd.yyyy
    
PARAMETERS:
   strValue - String to be tested for validity
   
RETURNS:
   True if valid, otherwise false.
   
REMARKS:
   Avoids some of the limitations of the Date.parse()
   method such as the date separator character.
*************************************************/
  var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
 
  //check to see if in correct format
  if(!objRegExp.test(strValue))
    return false; //doesn't match pattern, bad date
  else{
    var arrayDate = strValue.split(RegExp.$1); //split date into month, day, year
	var intDay = parseInt(arrayDate[1],10); 
	var intYear = parseInt(arrayDate[2],10);
    var intMonth = parseInt(arrayDate[0],10);
	
	//check for valid month
	if(intMonth > 12 || intMonth < 1) {
		return false;
	}
	
    //create a lookup for months not equal to Feb.
    var arrayLookup = { '01' : 31,'03' : 31, '04' : 30,'05' : 31,'06' : 30,'07' : 31,
                        '08' : 31,'09' : 30,'10' : 31,'11' : 30,'12' : 31}
  
    //check if month value and day value agree
    if(arrayLookup[arrayDate[0]] != null) {
      if(intDay <= arrayLookup[arrayDate[0]] && intDay != 0)
        return true; //found in lookup table, good date
    }
		
    //check for February
	var booLeapYear = (intYear % 4 == 0 && (intYear % 100 != 0 || intYear % 400 == 0));
    if( ((booLeapYear && intDay <= 29) || (!booLeapYear && intDay <=28)) && intDay !=0)
      return true; //Feb. had valid number of days
  }
  return false; //any other values, bad date
}

function IsvalidURL(imageURL)
{
		

		lengthValue = trimAll(imageURL);
		lengthValue = lengthValue.length;
		if(lengthValue != 0)
		{
		var j = new RegExp();
		j.compile("^[A-Za-z]+://[A-Za-z0-9-]+\.[A-Za-z0-9]+");             
		lengthValue = trimAll(imageURL);
	
		if (!j.test(lengthValue))
		{
			return false;
		}
		else
		{
			return true;
		}
		}
	
}

function validateValue( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Validates that a string a matches
  a valid regular expression value.
    
PARAMETERS:
   strValue - String to be tested for validity
   strMatchPattern - String containing a valid
      regular expression match pattern.
      
RETURNS:
   True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);
 
 //check if string matches pattern
 return objRegExp.test(strValue);
}


function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from 
  source string.
  
PARAMETERS: 
  strValue - Source string from which currency formatting
     will be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /\(/;
  var strMinus = '';
 
  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }
  
  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.

PARAMETERS: 
  strValue - Source string to be formatted

REMARKS: Assumes number passed is a valid 
  numeric value in the rounded to 2 decimal 
  places.  If not, returns original value.
*************************************************/
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
   
    if( objRegExp.test(strValue)) {
      objRegExp.compile('^-');
      strValue = addCommas(strValue);
      if (objRegExp.test(strValue)){
        strValue = '($' + strValue.replace(objRegExp,'') + ')';
      }
      else {
        strValue = '$' + strValue;
      }
      return  strValue;
    }
    else
      return strValue;
}

function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.

PARAMETERS: 
  strValue - Source string from which commas will 
    be removed;

RETURNS: Source string with commas removed.
*************************************************/
  var objRegExp = /,/g; //search for commas globally
 
  //replace all matches with empty strings
  return strValue.replace(objRegExp,'');
}

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS: 
  strValue - source string containing commas.
  
RETURNS: String modified with comma grouping if
  source was all numeric, otherwise source is 
  returned.
  
REMARKS: Used with integers or numbers with
  2 or less decimal places.
*************************************************/
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})'); 

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match, 
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
  based upon matches of the supplied pattern.

PARAMETERS: 
  strValue - source string containing number.
  
RETURNS: String modified with characters
  matching search pattern removed
  
USAGE:  strNoSpaces = removeCharacters( ' sfdf  dfd', 
                                '\s*')
*************************************************/
 var objRegExp =  new RegExp( strMatchPattern, 'gi' );
 
 //replace passed pattern matches with blanks
  return strValue.replace(objRegExp,'');
}
function is_valid_credit_card_number(cardNumber, cardType)//sample card type visa no 4992739871642 
{
	//alert(cardType);
	//alert(cardNumber);
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);
  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;
    switch(cardType.toLowerCase())
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;
	  case "discover":
		lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^6011/;
        break;  
      default:
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
		{
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }
  //isValid=true;
  return isValid;
}
this.isValidCardNumber = function(cardNumber, cardType) {
		  var isValid = false;
		  var ccCheckRegExp = /[^\d ]/;
		  isValid = !ccCheckRegExp.test(cardNumber);

		  if (isValid)
		  {
			var cardNumbersOnly = cardNumber.replace(/ /g,"");
			var cardNumberLength = cardNumbersOnly.length;
			var lengthIsValid = false;
			var prefixIsValid = false;
			var prefixRegExp;

			switch(cardType)
			{
			  case "mastercard","MasterCard":
				lengthIsValid = (cardNumberLength == 16);
				prefixRegExp = /^5[1-5]/;
				break;

			  case "visa","Visa":
				lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
				prefixRegExp = /^4/;
				break;

			  case "amex","Amex":
				lengthIsValid = (cardNumberLength == 15);
				prefixRegExp = /^3(4|7)/;
				break;
			  case "discover","Discover":
				lengthIsValid = (cardNumberLength == 16);
				prefixRegExp = /^6011/;
				break;  
			  default:
				prefixRegExp = /^$/;
				//alert("Card type not found");
			}

			prefixIsValid = prefixRegExp.test(cardNumbersOnly);
			isValid = prefixIsValid && lengthIsValid;
		  }

		  if (isValid)
		  {
			var numberProduct;
			var numberProductDigitIndex;
			var checkSumTotal = 0;

			for (digitCounter = cardNumberLength - 1; 
			  digitCounter >= 0; 
			  digitCounter--)
			{
			  checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
			  digitCounter--;
			  numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
			  for (var productDigitCounter = 0;
				productDigitCounter < numberProduct.length; 
				productDigitCounter++)
				{
				checkSumTotal += 
				  parseInt(numberProduct.charAt(productDigitCounter));
			  }
			}

			isValid = (checkSumTotal % 10 == 0);
		  }
		  //isValid=true;
		  return isValid;
	}
//function for validating credit card number

function is_valid_credit_card(cardNumber, cardType)//sample card type visa no 4992739871642 
{
	alert(cardType);
	alert(cardNumber);
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard","MasterCard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa","Visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex","Amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;
	  case "discover","Discover":
		lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^6011/;
        break;  
      default:
        prefixRegExp = /^$/;
        alert("Card type not found");
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
		{
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }
  //isValid=true;
   alert(isValid);
  return isValid;
}

//to check for numeric
function IsNumeric(sText)
{
   var ValidChars = "0123456789.,";
   var IsNumber=true;
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
		  Char = sText.charAt(i); 
		  if (ValidChars.indexOf(Char) == -1) 
		 {
			IsNumber = false;
		 }
      }
   return IsNumber;
}

function isValidDate(currentDate,controlDate)
{
	//alert(currentDate);
	var date1 = currentDate;
    var date2 = controlDate;
     
    var date3 = new Date();
    var date4 = date3.getMonth() + "/" + date3.getDay() + "/" + date3.getYear();
    var currentDate = new Date(date4);
   // alert(date2);
       if(date1 > date2)
       {
           //alert("fromdate should be less than todate");
           return false; 
       }
       else if(date1 > currentDate)
       {
          // alert("From Date should be less than current date");
           return false; 
       }
	  else if(date2 > currentDate) 
	  {
		 // alert("To Date should be less than current date");
			return false; 
	  }

		return true;
}

function funcValidateCreditCardNum(CreditCardNum)
{
	var ccNumb=CreditCardNum;
	var valid = "0123456789";
	var len = ccNumb.length;  
	var iCCN = parseInt(ccNumb);  
	var sCCN = ccNumb.toString();  
	sCCN = sCCN.replace (/^\s+|\s+$/g,'');  
	var iTotal = 0;  
	var bNum = true;  
	var bResult = false;  
	var temp;  // temp variable for parsing string
	var calc;  // used for calculation of each digit


	// ccNumb is a number and the proper length - let's see if it is a valid card number
	if(len >= 13 && len <=16)
	{  // 15 or 16 for Amex or V/MC					
			for(var i=len;i>0;i--)
				{  // LOOP throught the digits of the card
					  calc = parseInt(iCCN) % 10;  // right most digit
					  calc = parseInt(calc);  // assure it is an integer
					  iTotal += calc;  // running total of the card number as we loop - Do Nothing to first digit
					  i--;  // decrement the count - move to the next digit in the card
					  iCCN = iCCN / 10;                               // subtracts right most digit from ccNumb
					  calc = parseInt(iCCN) % 10 ;    // NEXT right most digit
					  calc = calc *2;                                 // multiply the digit by two
					  // Instead of some screwy method of converting 16 to a string and then parsing 1 and 6 and then adding them to make 7,
					  // I use a simple switch statement to change the value of calc2 to 7 if 16 is the multiple.
					  switch(calc)
					  {
						case 10: calc = 1; break;       //5*2=10 & 1+0 = 1
						case 12: calc = 3; break;       //6*2=12 & 1+2 = 3
						case 14: calc = 5; break;       //7*2=14 & 1+4 = 5
						case 16: calc = 7; break;       //8*2=16 & 1+6 = 7
						case 18: calc = 9; break;       //9*2=18 & 1+8 = 9
						default: calc = calc;           //4*2= 8 &   8 = 8  -same for all lower numbers
					  }                                               
					iCCN = iCCN / 10;  // subtracts right most digit from ccNum
					iTotal += calc;  // running total of the card number as we loop
				}  // END OF LOOP
		  if(! ((iTotal%10)==0))
			{
				return false;
			}	
	}	
	else
	{
		return false;
	}
}
function isCreditCard(textval) {
 /*
  *  This function validates a credit card entry.
  *  If the checksum is ok, the function returns true.
  */
   var ccNum;
   var odd = 1;
   var even = 2;
   var calcCard = 0;
   var calcs = 0;
   var ccNum2 = "";
   var aChar = '';
   var cc;
   var r;
   ccNum	=	textval;
   for(var i = 0; i != ccNum.length; i++) {
      aChar = ccNum.substring(i,i+1);
      if(aChar == '-') {
         continue;
      }

      ccNum2 = ccNum2 + aChar;
   }
   
   cc = parseInt(ccNum2);
   if(cc == 0) {
      return false;
   }
   r = ccNum.length / 2;
   if(ccNum.length - (parseInt(r)*2) == 0) {
      odd = 2;
      even = 1;
   }
   
   for(var x = ccNum.length - 1; x > 0; x--) {
      r = x / 2;
      if(r < 1) {
         r++;
      }
      if(x - (parseInt(r) * 2) != 0) {
         calcs = (parseInt(ccNum.charAt(x - 1))) * odd;
      }
      else {
         calcs = (parseInt(ccNum.charAt(x - 1))) * even;
      }
      if(calcs >= 10) {
         calcs = calcs - 10 + 1;
      }
      calcCard = calcCard + calcs;
   }
   
   calcs = 10 - (calcCard % 10);
   if(calcs == 10) {
      calcs = 0;
   }
   
   if(calcs == (parseInt(ccNum.charAt(ccNum.length - 1)))) {
      return true;
   }
   else {
      return false;
   }
}
function  containsURLCharacters( strValue ) {
	  var objRegExp  =  /(^[a-zA-Z0-9]+$)/; 
	  return objRegExp.test(strValue);
}
function  containssubCharacters( strValue ) {
	 var objRegExp  =  /(^[a-zA-Z0-9\:\/\ ]+$)/;   
	 return objRegExp.test(strValue);
}
function  containshtmlCharacters( strValue ) {
	 var objRegExp  =   /(^[a-zA-Z0-9\:\/\,\;\'\"\ \|\!\(\)\ ]+$)/; 
	 return objRegExp.test(strValue);
}
function  validate_urlcharacters( strValue ) {
 var objRegExp  =  /(^[a-zA-Z0-9\_\ ]+$)/; 
  return objRegExp.test(strValue);
}
function add_to_cart(productid){
	
	if(trimAll(document.getElementById('product_qty_'+productid).value) == ""){
		alert("Please enter product quantity.");
		document.getElementById('product_qty_'+productid).focus();
	}else if(!(validateInteger(document.getElementById('product_qty_'+productid).value))){
		alert("Please enter valid product quantity.");
		document.getElementById('product_qty_'+productid).focus();
	}else{
		document.getElementById('cart_'+productid).innerHTML = "<img src=images/loading.gif border=0>";
		document.productForm.cartproductID.value = productid;
		
		url = "ajax/cart.php?productID="+productid+"&qty="+document.getElementById('product_qty_'+productid).value+"&From=products";

		http_req = null;

		if (window.XMLHttpRequest)     http_req = new XMLHttpRequest();
		else if (window.ActiveXObject) http_req = new ActiveXObject("Microsoft.XMLHTTP");

		if (http_req)
		{
			http_req.onreadystatechange = processcart;
			http_req.open("GET", url, true);
			http_req.send("");
		}
	}
}
function processcart(){
	if(http_req.readyState == 4){
		var txt,DisplayText;			
		txt = http_req.responseText;
		
		var sValues = txt.split("||")
		document.getElementById('cart_'+sValues[0]).innerHTML   = "<img src=images/update_cart_bt.jpg border=0 style=cursor:pointer; OnClick=add_to_cart('"+sValues[0]+"')>";
		
		var productcaption;
		if(sValues[2] == "1"){
			productcaption = "product";
		}else{
			productcaption = "products";
		}
		document.getElementById('message').innerHTML = "<a href=shopping-cart.php class=siteblink>View Cart&nbsp;("+sValues[2]+")</a>";

	}	
}

//paging function
var nav4 = window.Event ? true : false;
function pagetransfer(pagenumber,Formname)
{
	with(document.forms[Formname])
	{
		hdn_page.value	= pagenumber;
		hdn_mode.value	= "paging";
		target="";
		action="";
		submit();
	}
}

function enter_paging(e,Formname,TotalPages)
{	if(nav4) 	
		{		var whichCode = e.which; 	 
		}
	 else
		 { 		
		 var whichCode = event.keyCode;	
		 }		
	if(whichCode == 13) 	
		{		
		if(valid_paging(Formname,TotalPages) == false)		
			{			
			return false;		
			}	
		}
}
function submit_form(FormName)
{
		document.forms[FormName].submit();
}
function valid_paging(Formname,TotalPages){			
	var Err_Message = "";
		with(document.forms[Formname]){	
				
			if(!(validateNotEmpty(page_Go.value))){
				alert('Enter page number');
				page_Go.focus();
				return false;
			}
			else if(!(parseCurrency(trimAll(page_Go.value))))
			{
				alert('Enter valid page number');
				page_Go.focus();
				return false;
			}
			else if(page_Go.value > TotalPages)
			{
				alert('Page does not exists');
				page_Go.focus();
				return false;
			}

			else if(!(validateNumeric(page_Go.value)))
			{
				alert('Enter valid page number');
				page_Go.focus();
				return false;
			}
			else
				{			
				pagetransfer(page_Go.value,Formname);	
				}
			return true;
		}
	}

 function fun_login()
 {
	 with(document.loginfrm)
	 {
		 if(trimAll(text_username.value)=="")
		 {
			 alert("Please enter username!");
			 text_username.focus();
			 return false;
		 }
		 else if(trimAll(text_pwd.value)=="")
		 {
			 alert("Please enter password!");
			 text_pwd.focus();
			 return false;
		 }
         submit();
         return true;
	 }

 }

 function getScreenLeft(width)
 {
    var left = parseInt((screen.availWidth/2) - (width/2));
	return left;
 }

 function getScreenTop(height)
 {
    var top = parseInt((screen.availHeight/2) - (height/2));
	return top;
 }
 function showPopUp(url,width,height)
 {
	var windowFeatures = "width=" + width + ",height=" + height + ",status,scrollbars,resizable,left=" + getScreenLeft(width) + ",top=" + getScreenTop(height) + "screenX=" + getScreenLeft(width) + ",screenY=" + getScreenTop(height);

	myWindow = window.open(url, "subWind", windowFeatures);
 }

    function selectall(pull_object)
    {
        if(pull_object.options[pull_object.selectedIndex].value == "ALL")
            for(i=1;i<pull_object.length;i++)
                pull_object[i].selected = true;
    }
 function find_browser() {
	var browser;
	if (checkIt('konqueror'))
	{
		browser = "Konqueror";
		OS = "Linux";
	}
	else if (checkIt('safari')) browser = "Safari"
	else if (checkIt('omniweb')) browser = "OmniWeb"
	else if (checkIt('opera')) browser = "Opera"
	else if (checkIt('webtv')) browser = "WebTV";
	else if (checkIt('icab')) browser = "iCab"
	else if (checkIt('msie')) browser = "IE"
	else if (!checkIt('compatible'))
	{
		browser = "Netscape Navigator"
	}
	else browser = "An unknown browser";

	if(browser == "Safari"){
		var b = navigator.userAgent.toLowerCase().split("/");
		var n =  b[2].split(" ");
		if(n[4] == 'chrome')
			browser = "chrome";
		else
			browser = "Safari";
	}
	return browser;
}

function getEle(elementID){
		return document.getElementById(elementID);
}
function checkIt(string){
	var detect = navigator.userAgent.toLowerCase();
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function clearAllErrors(){
	var aReturn=document.getElementsByTagName("DIV");
	for(i=0;i<aReturn.length;i++)
	{
		var cl = aReturn[i].className;
		if(cl.length>=9){
			cl = cl.substr(0,9);
			if(cl == "formError"){
				aReturn[i].className = "hideError";
				aReturn[i].innerHTML = "";
			}
		}
	}
}

//-----------------------------------------------------------------------------------------------------------------------------------

// wForms - a javascript extension to web forms.
// v0.99.23 - July 26 2005
// Copyright (c) 2005 Cédric Savarese <pro@4213miles.com>
// This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
// Other Contributors: Michael Duff (fullmoondesigns.net)



// Change Log: see http://formassembly.com/blog/wforms-a-javascript-extension-to-web-forms/

// v0.99.2  Fixed the refreshAllState / refreshState bug with multiple checkbox switches targeting the same element.
//			Fixed the checkOneRequired method. GetAttribute('value') didn't work in Firefox (thx to Bill Rafferty)
//			Added a SPAN element to the generated 'Repeat' and 'Delete' links to allow for CSS Image Replacement Technique
// 			Fixed Repeat behavior's 'find insert node' loop to handle server-side generated text-nodes (when populating a repeated group)
//			Changed default validation behavior in Safari (now always validate, but will break if used in conjunction w/ Switch or Paging behavior)
//			Added support for 'required' on a TABLE, TR or TD
//			Fixed Inline Event Handler in the Repeat behavior (for IE)
// Known Problems:
// 		Safari 1.x:  	Validation will run on invisible fields (switched off or w/ paging behavior. cf. checkVisibility())
// 		IE 5.2 Mac: 	Validation Disabled. currentStyle.display returns an empty string in checkVisibility() causing non-visible fields to get validated. 
//						Buggy Rendering of the Repeat behavior 
//						Counter Field of Repeat Behavior not submitted (probably setting the name attribute didn't work)
// 		IE 5.0 PC:		Repeat behavior doesn't work. All field are created as TEXT input ? To be checked again.

function wFORMS() { // wFORMS Class Constructor

	var wu = new wUTILITY();
	var self = this;

	// CSS class name definitions. 
	this.className_repeat 				= "repeat";
	this.className_delete 				= "removeable";
	this.className_duplicateLink 		= "duplicateLink";
	this.className_removeLink 			= "removeLink";
	// id attribute suffixes

	// Behavior configuration options
	this.preserveRadioName				= true; 				// if true, Repeat behavior will preserve name attributes for radio input. 
	this.switchScopeRootTag				= "FORM";				// limit the scope of the switch behavior. You may use 'BODY'.	
	this.functionName_formValidation = "this.formValidation";	// Form validation function name. May be overidden if you need to run your own validation routine (but make sure to run formValidation() in it).	
	this.showAlertOnError = false; 								// sets to false to not show the alert when a validation error occurs.
	this.preventSubmissionOnEnter = true; 						// prevents submission when pressing the 'enter' key. Set to true if pagination behavior is used.
	this.idSuffix_repeatCounter			= "_RC";

	// Other Messages
	this.arrMsg = new Array();
	this.arrMsg[0] = "Add another"; 	// repeat link
	this.arrMsg[1] = "Repeats the preceding field or field group." // title attribute on the repeat link 
	this.arrMsg[2] = "Remove"; 		// remove link
	this.arrMsg[3] = "Removes the preceding field or field group." // title attribute on the remove link
	this.utilities = wu;	
	

	// =======================================================================================
	// Repeat/Remove Behavior Methods
	// =======================================================================================

	// -------------------
	// Priviledged Methods
	// -------------------
	this.duplicateFieldGroup = function(e) {
		clearAllErrors();
		var srcE = wu.getSrcElement(e);
		// Get Element to duplicate.
		var sourceNode = srcE.parentNode;
		while (sourceNode && (!sourceNode.className || (' '+sourceNode.className+' ').indexOf(' '+self.className_repeat+' ') == -1)) {
			sourceNode = sourceNode.parentNode;
		}	
		if (sourceNode && sourceNode.className.indexOf(self.className_repeat) != -1) {
			// Extract row counter information
			counterField = document.getElementById(sourceNode.id + self.idSuffix_repeatCounter);
			if(!counterField) return; // should not happen.
			var rowCount = parseInt(counterField.value) + 1;
			//alert(rowCount);
			// Prepare id suffix
			var suffix = "_" + rowCount.toString()
			// duplicate node tree 
			var dupTree = replicateTree(sourceNode, null, suffix);  //  sourceNode.cloneNode(true); 
			// find insert point in DOM tree (after existing repeated element)
			var insertNode = sourceNode.nextSibling;
			while(insertNode && 
				  (insertNode.nodeType==3 ||       // skip text-node that can be generated server-side when populating a previously repeated group 
				   ( insertNode.nodeType==1 &&     
					 insertNode.className && 
					 insertNode.className.indexOf(self.className_delete) != -1))) {
				insertNode = insertNode.nextSibling;
			}
					
			sourceNode.parentNode.insertBefore(dupTree,insertNode);	 // Buggy rendering in IE5/Mac
			// if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1)			
			//
			
			// the copy is not duplicable, it's removeable
			dupTree.className = sourceNode.className.replace(self.className_repeat,self.className_delete);
			// Save new row count 			
			document.getElementById(sourceNode.id + self.idSuffix_repeatCounter).value = rowCount;
			// re-add behaviors
			if(!dupTree.id) dupTree.id = wu.randomId() + suffix;  //  createAttribute()
			wu.debug('Duplicated tree id : '+dupTree.id);
			self.addBehaviors(dupTree.id);
			
			// FAT support
			if(typeof Fat != 'undefined' && Fat && dupTree.id) Fat.fade_element(dupTree.id, 10, 600, "#FFFFCC", "#FFFFFF");	
		}
		return wu.XBrowserPreventEventDefault(e);
	}
	this.removeFieldGroup = function(e)
	{ 
		if(confirm("Are you sure?.Do you want to delete this?"))
		{
			var srcE = wu.getSrcElement(e);	// Get Element to remove.
			var delNode = srcE.parentNode;
			while (delNode && (' '+delNode.className+' ').indexOf(' '+self.className_delete+' ') == -1) 
			{
				delNode = delNode.parentNode;
			}
			delNode.parentNode.removeChild(delNode);
			clearAllErrors();
			return wu.XBrowserPreventEventDefault(e);
		}
		else
		{
			return false;
		}
	}

	// Repeat Behavior Private Methods
	// -------------------------------
	function removeRepeatCountSuffix(str) {
		return str.replace(/-\d$/,'');
	}
	
	function replicateTree(srcNode,dupParentNode, idSuffix) {
		switch(srcNode.nodeType) {
			case 1:	// ELEMENT-NODE
				if(srcNode.className.indexOf(self.className_duplicateLink) != -1 ||
					srcNode.className.indexOf(self.className_removeLink) != -1  ) 							
					return null; // Exclude the 'duplicate/remove' links
				if(srcNode.className.indexOf(self.className_delete) != -1) { 							
					return null; // Exclude duplicated elements of a nested repeat group
				}				 
				if(srcNode.className.indexOf(self.className_repeat) != -1 && dupParentNode!=null) { 
					// Match nested repeat group only
					idSuffix = idSuffix.replace('-','__');
				}
				   
				if(document.all && !window.opera) { 
					// IE Specific : see http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/name_2.asp
					var tagHtml = srcNode.tagName;
					
					if(srcNode.name) 					
						if (srcNode.tagName.toUpperCase()=="INPUT" && srcNode.type.toLowerCase()=="radio" && self.preserveRadioName)
							tagHtml += " NAME='" + srcNode.name + "' ";
						else
							tagHtml += " NAME='" + removeRepeatCountSuffix(srcNode.name) + idSuffix + "' ";
					if(srcNode.type) {
						tagHtml += " TYPE='" + srcNode.type + "' ";
					}
					if(srcNode.selected) 
						tagHtml += " SELECTED='SELECTED' ";
					if(srcNode.checked)
						tagHtml += " CHECKED='CHECKED' ";

					if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1) // IE5 Mac
						var newNode = document.createElement(tagHtml);
					else
						var newNode = document.createElement("<" + tagHtml + "></"+ srcNode.tagName + ">"); 
					try { newNode.type = srcNode.type; } catch(e) {}; // nail it down for IE5 ?, breaks in IE6
 					
				}
				else
					var newNode = document.createElement(srcNode.tagName); 
	
				// get attributes										
				for(var i=0; i< srcNode.attributes.length; i++) {
					// Get Attribute Value. Adjust it if necessary.
					if(	srcNode.attributes[i].specified || // in IE, the attributes array contains all attributes in the DTD
						srcNode.attributes[i].nodeName.toLowerCase() == 'value' ) { // attr.specified buggy in IE?  
	
						if(	srcNode.attributes[i].nodeName.toLowerCase() == "id" || 
							srcNode.attributes[i].nodeName.toLowerCase() == "name" ||
							srcNode.attributes[i].nodeName.toLowerCase() == "for") {
														
							if(srcNode.attributes[i].nodeValue.indexOf(self.idSuffix_fieldHint) != -1)  {
								//leave the field hint suffix at the end of the id.
								var value = srcNode.attributes[i].nodeValue;
								value= removeRepeatCountSuffix(value.substr(0,value.indexOf(self.idSuffix_fieldHint))) + idSuffix + self.idSuffix_fieldHint;
							}
							else {
								if (srcNode.tagName.toUpperCase()=="INPUT" && srcNode.getAttribute('type',false).toLowerCase()=="radio" &&
									srcNode.attributes[i].nodeName.toLowerCase() == "name" && self.preserveRadioName) {
									var value = srcNode.attributes[i].nodeValue;						
								}
								else {
									// var value = removeRepeatCountSuffix(srcNode.attributes[i].nodeValue) + idSuffix;
									var value = srcNode.attributes[i].nodeValue + idSuffix;
								}
							}
						} else {
							// Do not copy the value attribute for text/password/file input
							if(srcNode.attributes[i].nodeName.toLowerCase() == "value" &&
							 	srcNode.tagName.toUpperCase()=='INPUT' &&  
								  (srcNode.type.toLowerCase() == 'text' || srcNode.type.toLowerCase() == 'password' || srcNode.type.toLowerCase() == 'file')) {
								if(srcNode.alt == "UseDefault")
									var value = srcNode.value;
								else
									var value=''; 
							}
							else if(srcNode.attributes[i].nodeName.toLowerCase() == "value" &&
							 	srcNode.tagName.toUpperCase()=='INPUT' &&  
								  (srcNode.type.toLowerCase() == 'radio'))
							{
								var value = idSuffix.replace('_','');	
							}
							else
								var value = srcNode.attributes[i].nodeValue;
						}
						// Create attribute and assign value
						switch(srcNode.attributes[i].nodeName.toLowerCase()) {
							case "class":
								newNode.className = value; 
								break;
							case "style": // inline style attribute (fix for IE)
								if(srcNode.style && srcNode.style.cssText) newNode.style.cssText = srcNode.style.cssText; 
								break;								
							case "onclick": // inline event handler (fix for IE)
								newNode.onclick = srcNode.onclick;							
								break;							
							case "onchange":							
								newNode.onchange = srcNode.onchange;							
								break;							
							case "onsubmit":
								newNode.onsubmit = srcNode.onsubmit;							
								break;							
							case "onmouseover":							
								newNode.onmouseover = srcNode.onmouseover;							
								break;							
							case "onmouseout":							
								newNode.onmouseout = srcNode.onmouseout;							
								break;							
							case "onmousedown":
								newNode.onmousedown = srcNode.onmousedown;							
								break;							
							case "onmouseup":
								newNode.onmouseup = srcNode.onmouseup;							
								break;							
							case "ondblclick":
								newNode.ondblclick = srcNode.ondblclick;							
								break;							
							case "onkeydown":
								newNode.onkeydown = srcNode.onkeydown;							
								break;							
							case "onkeyup":
								newNode.onkeyup = srcNode.onkeyup;							
								break;							
							case "onblur":
								newNode.onblur = srcNode.onblur;							
								break;							
							case "onfocus":
								newNode.onfocus = srcNode.onfocus;							
								break;
							default:
								//if(srcNode.attributes[i].name != 'value') {
								//	alert(srcNode.attributes[i].name + " " + value);
								//}
								newNode.setAttribute(srcNode.attributes[i].name, value, 0);//setAttribute(newNode, srcNode.attributes[i].name, value);
						}
					}
				}				
				break;
			case 3: // TEXT-NODE (do not copy value of textareas)
				if(srcNode.parentNode.tagName.toUpperCase() != 'TEXTAREA')
					var newNode = document.createTextNode(srcNode.data); 
				break;
		}
		if(dupParentNode && newNode) dupParentNode.appendChild(newNode);
		for(var i=0; i<srcNode.childNodes.length;i++) {
			replicateTree(srcNode.childNodes[i],newNode,idSuffix);
		}
		return newNode;
	}
		

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


}

//------------------------------------------------------------------------------------------------------------------------
// WFORMS Public Methods
//------------------------------------------------------------------------------------------------------------------------
wFORMS.prototype.onLoadHandler = function() {		
	for (var i=0;i<document.forms.length;i++) {
		if(!document.forms[i].id) document.forms[i].id = this.utilities.randomId();
		this.addBehaviors(document.forms[i].id);
	}
}
wFORMS.prototype.addBehaviors = function (fId) {
	var f=document.getElementById(fId);
	if(!f) return;

	var thisForm; 				// Pointer to keep track of the current form being processed.
	var wu = this.utilities;	// Utiltiy class instance
	wu.resetEventList();
	
	// loop through the fields
	var x = wu.getElements(f);
	
	for (var i=0;i<x.length;i++) {

		// add repeat behavior
		if (x[i].className && (' '+x[i].className+' ').indexOf(' '+this.className_repeat+' ') != -1) {
			// this element to be duplicated.
			wu.debug('adding repeat on ' + x[i].id);
			var actionNode = null;
			if(x[i].id) actionNode = document.getElementById(x[i].id + this.idSuffix_duplicateLink);
			if (!actionNode) {				
				// add duplicate action
				actionNode = document.createElement("a"); 
				var spanNode = document.createElement("span");  // For CSS image replacement 
				var textNode = document.createTextNode(this.arrMsg[0]);
				actionNode.setAttribute('href',"#");	
				actionNode.className = this.className_duplicateLink;			
				actionNode.setAttribute('title', this.arrMsg[1]);	
				if(x[i].tagName.toUpperCase()=="TR") {
					// find the last TD
					var n = x[i].lastChild;	
					while(n && n.nodeType != 1)  
						n = n.previousSibling;
					if(n && n.nodeType == 1) 
						n.appendChild(actionNode);
					// Else Couldn't find the TD. Table row malformed ?
				} else
					x[i].appendChild(actionNode);
					
				spanNode.appendChild(textNode); 
				actionNode.appendChild(spanNode); 
			}
			// Add hidden counter field if necessary
			var counterField = document.getElementById(x[i].id + this.idSuffix_repeatCounter);
			if (!counterField) {
				if(document.all && !window.opera) { // IE Specific :-(
					// see http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/name_2.asp
					var counterFieldId = x[i].id + this.idSuffix_repeatCounter;
					if(navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") == -1) // IE5 Mac
						counterField = document.createElement("INPUT NAME=\"" + counterFieldId + "\"");
					else
						counterField = document.createElement("<INPUT NAME=\"" + counterFieldId + "\"></INPUT>"); 					
					counterField.type='hidden';
					counterField.id = counterFieldId; 
					counterField.value = "1";
				}
				else {
					counterField = document.createElement("INPUT"); 
					counterField.setAttribute('type','hidden'); // hidden
					counterField.setAttribute('value','1');
					counterField.setAttribute('name', x[i].id + this.idSuffix_repeatCounter);
					counterField.setAttribute('id', x[i].id + this.idSuffix_repeatCounter); 
				}
				
				if(!thisForm) {
					thisForm = x[i].parentNode;
					while(thisForm && thisForm.tagName.toUpperCase() != "FORM")
						thisForm = thisForm.parentNode;
				}
				
				thisForm.appendChild(counterField);
			}
			// Add event handler			
			wu.XBrowserAddHandler(actionNode,'click',this.duplicateFieldGroup);			
		}	
		// add remove behavior
		if (x[i].className && (' '+x[i].className+' ').indexOf(' '+this.className_delete+' ') != -1) {
			wu.debug('adding remove on ' + x[i].id);
			// this element can be removed
			// add remove action
			var actionNode = document.createElement("a");
			var spanNode = document.createElement("span");  // For CSS image replacement 
			var textNode = document.createTextNode(this.arrMsg[2]);
			actionNode.setAttribute('href',"javascript:");	
			actionNode.className = this.className_removeLink;
			actionNode.setAttribute('title',this.arrMsg[3]);	
			if(x[i].tagName.toUpperCase()=="TR") {
				// find the last TD
				var n = x[i].lastChild;	
				while(n && n.nodeType != 1)  
					n = n.previousSibling;
				if(n && n.nodeType == 1) 
					n.appendChild(actionNode);
				// Else Couldn't find the TD. Table row malformed ?
			} else
				x[i].appendChild(actionNode);
			spanNode.appendChild(textNode); 
			actionNode.appendChild(spanNode); 	
			wu.XBrowserAddHandler(actionNode,'click',this.removeFieldGroup);			
		}	
	 }
}


// *************************************************************************************************************
// UTILITY CLASS
// *************************************************************************************************************
function wUTILITY() {
	// Event Handler utility list
	this.handlerList = new Array(); 
}

// Cross-Browser event handler management.
// adapted from Andy Smith's (http://weblogs.asp.net/asmith/archive/2003/10/06/30744.aspx)
wUTILITY.prototype.XBrowserAddHandler = function (target,eventName,handlerName) {
	if(!target) return;
	if (target.addEventListener) { 
		target.addEventListener(eventName, function(e){eval(handlerName)(e);}, false);
	} else if (target.attachEvent) { 
		target.attachEvent("on" + eventName, function(e){eval(handlerName)(e);});
		} else { 
		// THIS CODE NOT TESTED 
		var originalHandler = target["on" + eventName]; 
		if (originalHandler) { 
		  target["on" + eventName] = function(e){originalHandler(e);eval(handlerName)(e);}; 
		} else { 
		  target["on" + eventName] = eval(handlerName); 
		} 
	} 
	// Keep track of added handlers.
	var l = this.handlerList.length;
	this.handlerList[l] = new Array(2);
	this.handlerList[l][0] = target.id;  
	this.handlerList[l][1] = eventName;  	
	this.debug("Handler added :" + target.id + ' ' + eventName);
}
// 
wUTILITY.prototype.isEventHandled = function(n, type) {	
	for(var i=0; i < this.handlerList.length; i++) {
		if(this.handlerList[i][0]==n.id && this.handlerList[i][1]==type)
			return true;
	}
	return false;
}
wUTILITY.prototype.resetEventList = function() {
	this.handlerList = new Array(); 
}

// Activating an Alternate Stylesheet (thx to: http://www.howtocreate.co.uk/tutorials/index.php?tut=0&part=27)
// Use this to activate a CSS Stylesheet that shouldn't be used if javascript is turned off.
// The stylesheet rel attribute should be 'alternate stylesheet'. The title attribute should be set.
wUTILITY.prototype.activateStylesheet = function(sheetref) {
	if(document.getElementsByTagName) {
		var ss=document.getElementsByTagName('link');
	} else if (document.styleSheets) {
		var ss = document.styleSheets;
	}
	for(var i=0;ss[i];i++ ) {
		if(ss[i].href.indexOf(sheetref) != -1) {
			ss[i].disabled = true;
			ss[i].disabled = false;			
		}
	}
}
// Generates a random ID
wUTILITY.prototype.randomId = function () {
	var rId = "";
	for (var i=0; i<6;i++)
		rId += String.fromCharCode(97 + Math.floor((Math.random()*24)))
	return rId;
}
// returns all child elements of a node.
wUTILITY.prototype.getElements = function(n, list) {
	if(!list) list = new Array();
	if(n.nodeType==1) {
		list[list.length]= n;
		for(var i=0; i<n.childNodes.length;i++) 
			this.getElements(n.childNodes[i], list);
		return list;
	}
}
// Returns the event's source element 
wUTILITY.prototype.getSrcElement = function(e) {	
	if(!e) 
		e = window.event;	
	if(e.target)
		var srcE = e.target;
	else
		var srcE = e.srcElement;
	if(srcE.nodeType == 3) srcE = srcE.parentNode; // safari weirdness		
	if(srcE.tagName.toUpperCase()=='LABEL') { 
		// when clicking a label, firefox fires the input onclick event
		// but the label remains the source of the event. In Opera and IE 
		// the source of the event is the input element. Which is the 
		// expected behavior, I suppose.		
		if(srcE.getAttribute('for')) {
			srcE = document.getElementById(srcE.getAttribute('for'));
		}
	}
	return srcE;
}
// Cancel the default execution of an event.
wUTILITY.prototype.XBrowserPreventEventDefault = function(e) {
	if(!e) e = window.event;
	if (e.preventDefault) e.preventDefault();
	else e.returnValue = false;
	return false;
}
wUTILITY.prototype.checkVisibility = function(n) {
	// check if any of the element's ancestors is not visible.
	if(window.getComputedStyle) {
		var isVisible = window.getComputedStyle(n,"").getPropertyValue("display").toLowerCase()!="none";
		isVisible = isVisible && window.getComputedStyle(n,"").getPropertyValue("visibility").toLowerCase()!="hidden";
		// add visiblity!=collapse ?
	}
	else if(n.currentStyle) {		
		if(n.currentStyle.display=='') return false; // effectively disable validation on IE5/Mac.
		var isVisible = n.currentStyle.display.toLowerCase() != "none";
		isVisible = isVisible && n.currentStyle.visibility.toLowerCase() !="hidden";
	}
	else {
		return true; 
		// use return false to disable validation if a switch or paging behavior is used.
	}
	if(!n.parentNode) { return false; } ; // should not happen, unless we're checking some removed elements.
	if (n.parentNode.tagName.toUpperCase()=="BODY" || !isVisible)
		return isVisible;
	return this.checkVisibility(n.parentNode);
}
	
wUTILITY.prototype.debug = function(text) { 
	var debugOutput = document.getElementById('debugOutput');  
	if(debugOutput) debugOutput.innerHTML = debugOutput.innerHTML+"<br />"+text; 
}

// =======================================================================================================================
// LET's GO
var wf = new wFORMS();
// Attach JS only stylesheet.
wf.utilities.activateStylesheet('wforms-jsonly.css'); 
// onLoad event handler
wf.utilities.XBrowserAddHandler(window,'load',function() { wf.onLoadHandler();}  );





function hopStopClose(){
	window.close();
	//window.opener.document.FrmAppointment.hdn_action.value="update";
	window.opener.document.getElementById('btn_submit_finish').onClick = function(){};
	window.opener.document.getElementById('btn_submit_finish').click();
	//window.opener.document.FrmAppointment.submit();
}