/*
+------------------------------------------------------------------+ 
Author(s): RST Team                                      
Last Modified Date: 02th December 2004.
File Purpose : Checking the javascript validation
+-------------------------------------------------------------------+ 

		Function 1: GenValidation(Element,Message1,Message2,spl)
		
			Message1: If you want to check the validation for the null 
			          or the element value is empty, what messge to be popped up.
			          
			Message2: If you want to check the validation for the element
			          length is less than 4, what messge to be popped up.
			          
			spl: Whether your element vlaue is to be checked for spl. characters			          
			          
			Usage  Details:
			
			Case 1: GenValidation(Element,'Message1','Message2','spl')		
			
			Case 2: GenValidation(Element,'','','spl')
			
			Case 3: GenValidation(Element,'','Message2','spl')
			
			Case 4: GenValidation(Element,'','Message2','')
			
			Case 5: GenValidation(Element,'Message1','','spl')

			Case 6: GenValidation(Element,'Message1','','')
			    
		Function 2: SplCharacters(Element)
					
		Function 3: EmailValidation(Element)
		
		Function 4: SplNumbers(Element)
		
		Function 5: NumValidation(Element,'Message','spl','num')
		
		Function 6: SelectValidation(Element,'Message')
		  	    This is to valid the select option values, 
		  	    always use your first option value is equals to zero
		example:		  	    
		  	    <select>
		  	    	<option value="0">select</option>
		  	    	<option value="1">......</option>
		  	    </select>
				
		Function 7: PassValidation(Element1,Element2)
					Retype Password and Password matching
					
		Function 8: isDate(Element)
					
		Function 9: ValidatePhone(element) used with onkeypress

		Function 10: SelectAll(form name)
		             
		             ex:-
		             <input type="checkbox" name="selectall" value="Select All" onclick="SelectAll(this.form);">
			     NOTE: The check box name should be "selectall"
			     
		Function 11: getSelectedIndex(radgroup)
					This can used while validating radio button groups. If none of the buttons is selected then the function	
					returns -1 else the id.
					
					E.g: frm is the name of a form and radSearchType is the radiobutton group name.
					
					if( getSelectedIndex(frm.radSearchType) == -1 )
					{
						alert("Please select search type." );
						frm.radSearchType[0].focus();
						return;
					}
		Function 12: TextareaValidation(elem,msg,len)
					This function can be used to validate the length of Text area's in forms.
					For example...if the value of text area should not exceed 500 characters.
					
					Arguments :
					elem : The element(TextArea)
					msg : Message to be alerted
					      For example "Description"
					len : Noof characters not to be exceeded
					
					E.g: frm is the name of a form and desc is a text area name.
					
					Usage in form: 
					if(TextareaValidation(frm.desc,'Description',500) == 0)
					return;
					
					if(elem.value.length > len) {
					   alert(msg+" should not exceed "+len+" characters");
					   elem.focus();
					   return 0;
					}			
		
		Function 13:rem_spaces(inputString)


		Function 14:rem_zero(inputString)

	CODE META DATA ENDS_______________________________________________
*/
/**
FUNCTION GENVALIDATION(element.message1,message2,spl) 
**/
	var dtCh= "/";
	armor_date=new Date()
	var minYear=2000;
	var maxYear=3000;
	function GenValidation(Element,MessageLen0,MessageLen4,spl) {
		
		if(MessageLen0.length != 0)
		{
			if(Element.value.length == 0)
			{
				alert("Please enter the "+ MessageLen0);
				Element.focus();
				return 0;
			}
			else if(isBlank(Element.value))
			{
				alert("Please enter the "+ MessageLen0);
				Element.focus();
				return 0;
			}
		}
	
		if(MessageLen4.length != 0)
		{
			if(Element.value.length < 4)
			{
				alert( MessageLen4 + " should be more than 4 characters");
				Element.focus();
				return 0;
			} // closing the if - else condtion for if(MessageLen4.length != 0)
		}
	
		if(spl == "spl")
		{
			if(SplCharacters(Element) == 0)
			return 0;
		}
		else if(spl == "space")
		{
			if(SplCharactersSpace(Element) == 0)
			return 0;
		}
	} // closing the function GenValidation()
	
	
	/**
	 FUNCTION SPLCHARACTERS(element) 
	 **/
	
	function SplCharacters(Val) {
	
		var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
	
		for (var i=0;i<Val.value.length;i++){
			temp=Val.value.substring(i,i+1);
			if (alp.indexOf(temp)==-1){
				alert("No special characters \nValid entries are [a-z][A-Z][0-9][ _ ]");
				Val.focus();
				return 0;
			}
		} // closing the for loop
	
	} // closing the function SplCharacters()
	
	/**
	 FUNCTION SPLCHARACTERS(element) 
	 **/
	
	function SplCharactersSpace(Val)
	{
		var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
	
		for (var i=0;i<Val.value.length;i++){
			temp=Val.value.substring(i,i+1);
			if (alp.indexOf(temp)==-1){
				alert("No special characters \nValid entries are [a-z][A-Z][0-9][ space ]");
				Val.focus();
				return 0;
			}
		} // closing the for loop
	} // closing the function SplCharactersSpace()
	
	/**
	 FUNCTION SPLNUMBERS(element) 
	 **/
	
	function SplNumbers(Val)
	{
		var alp = "0123456789+-";
	
		for (var i=0;i<Val.value.length;i++){
			temp=Val.value.substring(i,i+1);
			if (alp.indexOf(temp)==-1){
				alert("No special characters \nValid entries are [0-9][ + - ]");
				Val.focus();
				return 0;
			}
		} // closing the for loop
	
	} // closing the function SplNumbers()
	
	
	/**
	 FUNCTION FOR CHECKING THE FIELD CONTAINS BLANK VALUES ISBLANK(Element.value)
	 **/
	//To check if trim(value) is blank
function isBlank(txt, minlen)
{
	/*
		This fucntion can be used to check if a given text contains only spaces or 0 in length.

		INPUT: Text [txt]
					Minimum Length [minlen] optional
					Indicates that the text should be atleast 'minlen' in length

		OUTPUT: returns true if blank else false
	*/

	if( txt.length == getCountOf('\n', txt) )
	{
		/*
			This condition avoids the entry of just newlines in text areas.
		*/
		return true;
	}

	if( txt.length == getCountOf(' ', txt) || txt.length == 0 )
	{
		return true;
	}
	else if( minlen > 0 )
	{
		if( txt.length < minlen )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}
	
	//This can be used for any character validation.
	//For example in a valid date the count of - or / should not be more than 2
	//Likewise in a valid numer there should be only one .
	function getCountOf(vChr, txt)
	{
		var i = 0;
		var iCount = 0;
	
		for( i=0; i < txt.length; i++ )
		{
			if( txt.charAt(i) == vChr )
			{
				iCount++;
			}
		}
		return iCount;
	}
	
	
	function getSelectedIndex(radgroup)
	{
		/* Returns back the id of selected radio button in a radio button group  */
		var j = -1;
	
		for( i=0; i < radgroup.length; i++ )
		{
			if( radgroup[i].checked )
			{
				j = i;
			}
		}
		return j;
	}
	
	/**
	 FUNCTION TEXTAREAVALIDATION(element,message,len) 
	 **/
	
	function TextareaValidation(elem,msg,len) {
	
		   if(elem.value.length > 0)
		   {
			if(isBlank(elem.value)) 
			{
				alert("Please enter the value");
				elem.focus();
				return 0;
			}else if(elem.value.length > len) 
			{
				alert(msg+" should not exceed "+len+" characters");
				elem.focus();
				return 0;
			}	
		   }
		
	} // closing the function TextareaValidation()
	
	
	function checkInCharSet(txt, charset)
	{
		/*
			This function checks if the characters in a given text are part of a given character set.
	
			INPUT:	Text ti be verified [txt]
						String of character that forms the reference [charset]
	
			OUTPUT: Returns true if all of the characters in txt are part of charset, else false.
	
			USAGE:
						for example:
	
							checkInCharSet( "guru", "aeiouAEIOU" ) this fucntion returns false as "guru" contains 'g' and 'r'
							whcih are not part of "aeiouAEIOU".
	
							checkInCharSet( "abC", "abcdefABCDEF" ) this statement returns true as all "abC" contains characters
							that are present in "abcdefABCDEF"
		*/
	
		var b = true;
	
		for(i = 0; i < txt.length; i++ )
		{
			if( charset.indexOf(txt.charAt(i)) == -1 )
			{
				b = false;
			}
		}
	
		return b;
	}




/**
	 FUNCTION EMAILVALIDATION(element) 
	 **/
	 
	function EmailValidation(Element)
	{
		Flag  = 1;
		count = 0;
	
		var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_@.-";
		
		if(Element.value.length > 0)
		{
			for (var i=0; i<Element.value.length; i++)
			{
				temp = Element.value.substring(i, i+1);
	
				if (alp.indexOf(temp) == -1)
				{
					Flag = 0;
				}
			} // closing the for loop
		}
		else
		{
			Flag = 0;
		}
	
		for(var i=0; i <= Element.value.length; i++)
		{
			if(Element.value.charAt(0)=='@')
			{
				Flag = 0;
				break;
			}

			if(Element.value.charAt(Element.value.length-1)=='@')
			{
				Flag = 0;
				break;
			}

			if(Element.value.charAt(i)=='@') 
			{
				count = count + 1;

				if(count>1)
				{
					Flag = 0;
					break;
				}
			  
				if((Element.value.charAt(i-1)=='.') || (Element.value.charAt(i+1)=='.'))
				{
					Flag = 0;
					break;
				}
			}
			if(Element.value.indexOf('@')==-1)
			{
				Flag = 0;		    	
				break;
			}
			if(Element.value.charAt(0)=='.')
			{
				Flag = 0;
				break;
			}
			if(Element.value.indexOf('.')==-1)
			{
				Flag = 0;		    	
				break;
			}
		  } //closing the for loop
		
		if(Element.value.charAt(Element.value.length-1) == '.')
			Flag = 0;
			
		if(Flag != 1)
		{
			alert("Invalid Email Address.\nValid Characters [a-z][A-Z][0-9][ _ @ . - ].\n\nlike test@test.com, test1942@test.co.uk ...");
			Element.focus();
			return 0;
		}	
		else
			return 1;
	}
	
	
/**
	 FUNCTION SELECTVALIDATION(element,message) 
	 **/
	
	function SelectValidation(Element,Message) {
		if(Element.value == "0") {
			alert("Please select "+Message+" from the list");
			Element.focus();
			return 0;
		}
	
	}//// closing the function SELECTVALIDATION
	
	
	/**
	 FUNCTION PASSVALIDATION(element1,element2) 
	 **/
	
	function PassValidation(Element1,Element2) {
	
		if(Element1.value != Element2.value) {
			alert("Retype Password doesn't match");
			Element2.focus();
			return 0;
		}
		else
			return 1;
		
	} // closing the function PassValidation()
	
	
	
	/**
	FUNTION SELECTALL CHECK BOXES
	**/
	function SelectAll(frm) {
	 	   if(frm.selectall.checked == true) {
	 		 for(i=0;i<frm.elements.length;i++) {
		   if((frm.elements[i].type == "checkbox") && (frm.elements[i].name != "selectall")) {
			 frm.elements[i].checked = true;
		   } 
		 } 
	   }
	   else if(frm.selectall.checked == false) {
		
		  for(i=0;i<frm.elements.length;i++) {
			 if((frm.elements[i].type == "checkbox") && (frm.elements[i].name != "selectall")) {
			   frm.elements[i].checked = false;
			 } 
		  } 
	   } 
	} // closing the function SelectAll()
	
	
	
	/**
	 FUNCTION NUMVALIDATION(element,message,spl,onlynum) 
	 **/
	function NumValidation(Element, MessageLen0, spl, OnlyNum)
	{
		if(MessageLen0.length != 0)
		{
			if(isBlank(Element.value) || Element.value.length == 0)
			{
				alert("Please enter the "+ MessageLen0);
				Element.focus();
				return 0;
			}
		}
		
		if(OnlyNum == "num")
		{
			if(isNaN(Element.value))
			{
				alert("Please enter only Numeric Data");
				Element.focus();
				return 0;
			}
			if(parseInt(Element.value) < 0)
			{
				alert("Negative values are not allowed for this field.");
				Element.focus();
				return 0;
			}
		}
				
		if(spl == "spl" && OnlyNum != "num")
		{
			if(SplNumbers(Element) == 0)
			return 0;
		}	
	
	
	} // closing the function NumValidation()
	
	/*
			This fucntion can be used for date validations.
	*/		
	
	function isDate(dtStr){

	var daysInMonth = DaysArray(12)

	var pos1=dtStr.indexOf(dtCh)

	var pos2=dtStr.indexOf(dtCh,pos1+1)

	var strMonth=dtStr.substring(0,pos1)

	var strDay=dtStr.substring(pos1+1,pos2)

	var strYear=dtStr.substring(pos2+1)
   	
	strYr=strYear

	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)

	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)

	for (var i = 1; i <= 3; i++) {

		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)

	}

	month=parseInt(strMonth)

	day=parseInt(strDay)

	year=parseInt(strYr)

	if (pos1==-1 || pos2==-1){

		alert("The date format should be : mm/dd/yyyy")

		return false

	}

	if (strMonth.length<1 || month<1 || month>12){

		alert("Please enter a valid month")

		return false

	}

	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){

		alert("Please enter a valid day")

		return false

	}

	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
       
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)

		return false

	}

	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){

		alert("Please enter a valid date")

		return false

	}

return true

}//end of function isDate


function daysInFebruary (year){

	// February has 29 days in any year evenly divisible by four,

    // EXCEPT for centurial years which are not also divisible by 400.

    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );

}//end of function daysInFebruary 

function DaysArray(n) {

	for (var i = 1; i <= n; i++) {

		this[i] = 31

		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}

		if (i==2) {this[i] = 29}

   } 

   return this

}//end of function DaysArray()





//functions to check for valid date
function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;

}//end of function isInteger


//telephone validations


//check the telephone number in(###)###-######
function ValidatePhone(m){
p=m.value
if(p.length>12)
{
	alert("Invalid input only 12 numbers allowed");
	return false;
}
if (event.keyCode < 48 || event.keyCode > 57)
	{
	  	alert("Invalid input only numeric values accepted");
		event.returnValue = false;
	}
if(p.length==3){
        pp=p;
        d4=p.indexOf('(')
        d5=p.indexOf(')')
        if(d4==-1){
                pp="("+pp;
        }
        if(d5==-1){
                pp=pp+")";
        }
        m.value="";
        m.value=pp;
}
if(p.length>3){
        d1=p.indexOf('(')
        d2=p.indexOf(')')
        if (d2==-1){
                l30=p.length;
                p30=p.substring(0,4);
                p30=p30+")"
                p31=p.substring(4,l30);
                pp=p30+p31;
                m.value="";
                m.value=pp;
        }
}
if(p.length>5){
        p11=p.substring(d1+1,d2);
        if(p11.length>3){
             p12=p11;
             l12=p12.length;
             l15=p.length
             p13=p11.substring(0,3);
             p14=p11.substring(3,l12);
             p15=p.substring(d2+1,l15);
             m.value="";
             pp="("+p13+")"+p14+p15;
             m.value=pp;
        }
        l16=p.length;
        p16=p.substring(d2+1,l16);
        l17=p16.length;
        if(l17>3&&p16.indexOf('-')==-1){
                p17=p.substring(d2+1,d2+4);
                p18=p.substring(d2+4,l16);
                p19=p.substring(0,d2+1);
        pp=p19+p17+"-"+p18;
        m.value="";
        m.value=pp;
        }
}

}//end of function ValidatePhone()

function testphone(obj1){
         p=obj1.value
         p=p.replace("(","")
         p=p.replace(")","")
         p=p.replace("-","")
         p=p.replace("-","")
         if (isNaN(p)==true){
                  alert("Check phone");
                  return false;
         }
}//end of function testphone


//explain the field useage

function explain(name, output, msg) {
newwin = window.open('','','top=150,left=150,width=325,height=300');
if (!newwin.opener) newwin.opener = self;
with (newwin.document)
{
open();
write('<html>');
write('<body onLoad="document.form.box.focus()"><form name=form>' + msg + '<br>');
write('<p>You may enter your ' + name + ' here and it will be copied into the form for you.');
write('<p><center>' + name + ':  <input type=text name=box size=10 onKeyUp=' + output + '=this.value onBlur=close()>');
write('<p><input type=button value="Click to close when finished" onClick=window.close()>');
write('</center></form></body></html>');
close();
   }

}//end of function explain


//function for checking the currency format
function currencyFormat(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;  // Enter
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}//end of function currencyFormat


//This script accepts a number or string and formats it like U.S. currency. 
//Adds the dollar sign, rounds to two places past the decimal, adds place holding zeros, and commas where appropriate.

function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
cents = "0" + cents;
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + '$' + num + '.' + cents);
}




//function to Forms: Accept Terms 

function checkCheckBox(f){
if (f.agree.checked == false )
{
alert('Please check the box to continue.');
return false;
}else
return true;
}//end of function checkCheckBox



function rem_spaces(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }

   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { 
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { 
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); 
   }
   return retValue; 

}//end of function rem_spaces



function rem_zero(inputString) {
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { 
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }

   ch = retValue.substring(retValue.length-1, retValue.length);
   return retValue; 

}//end of function rem_zero

	function PwdValidation(Val)
	{
		var alp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@*#_";
	    if(Val.value.length<=0)
		 {
		   alert("Password Should not be null.");
		   return 0;
		 }
		for (var i=0;i<Val.value.length;i++){
			temp=Val.value.substring(i,i+1);
			if (alp.indexOf(temp)==-1){
				alert("Valid special characters for password are \n [a-z][A-Z][0-9][@][* # _]");
				Val.focus();
				return 0;
			}
		} // closing the for loop
	
	} // closing the functionPwdValidation()
	
function stripCharsInBag (s, bag)
{   
	var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}
function isValidZip(vZip)
{
	if (isNaN(vZip)  ||  (vZip.length != 5))
	{
			return false;
	}
	else
	{
		return true;
	}
}
function fixPhone(fld,fname,sep,noext)
{ 
// tenacious phone # correction 
  // blank fields are the domain of requireValue 
  if(typeof(sep)=='undefined') sep= '-';
  var ext= '', val= fld.value.toLowerCase();
  if(val.indexOf('x') > 0)
  {
    if(!noext) ext= ' x'+val.substr(val.indexOf('x')).replace(/\D/g,'');
    val= val.substr(0,val.indexOf('x'));
  }
  val= val.replace(/\D/g,'');
  if(val.length < 7)
  {
   alert('The phone number you supplied for the '+fname+' field was not proper.');
    return false;
  }
  if(val.length > 10)
  {
    alert('The phone number you supplied for the '+fname+' field was too long.');
    return false;
  }
  if(val.length == 10)
  {
    fld.value= val.substring(0,3) + sep + val.substring(3,6) + sep + val.substring(6,20) + ext;
    return true;
  }
  alert('The phone number you supplied for the '+fname+' field was wrong.');
  return false;
}
function isCreditCard(st) {
 // Encoding only works on cards with less than 19 digits
 if (st.length > 19)
   return (false);

 sum = 0; mul = 1; l = st.length;
 for (i = 0; i < l; i++) {
   digit = st.substring(l-i-1,l-i);
   tproduct = parseInt(digit ,10)*mul;
   if (tproduct >= 10)
     sum += (tproduct % 10) + 1;
   else
     sum += tproduct;
   if (mul == 1)
     mul++;
   else
     mul--;
 }
 
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

 if ((sum % 10) == 0)
   return (true);
 else
   return (false);

} // END FUNCTION isCreditCard()



/*  ================================================================
   FUNCTION:  isVisa()

   INPUT:     cc - a string representing a credit card number

   RETURNS:  true, if the credit card number is a valid VISA number.

          false, otherwise

   Sample number: 4111 1111 1111 1111 (16 digits)
   ================================================================ */

function isVisa(cc)
{
 if (((cc.length == 16) || (cc.length == 13)) &&
     (cc.substring(0,1) == 4))
   return isCreditCard(cc);
 return false;
}  // END FUNCTION isVisa()




/*  ================================================================
   FUNCTION:  isMasterCard()

   INPUT:     cc - a string representing a credit card number

   RETURNS:  true, if the credit card number is a valid MasterCard
            number.

          false, otherwise

   Sample number: 5500 0000 0000 0004 (16 digits)
   ================================================================ */

function isMasterCard(cc)
{
 firstdig = cc.substring(0,1);
 seconddig = cc.substring(1,2);
 if ((cc.length == 16) && (firstdig == 5) &&
     ((seconddig >= 1) && (seconddig <= 5)))
   return isCreditCard(cc);
 return false;

} // END FUNCTION isMasterCard()





/*  ================================================================
   FUNCTION:  isAmericanExpress()

   INPUT:     cc - a string representing a credit card number

   RETURNS:  true, if the credit card number is a valid American
            Express number.

          false, otherwise

   Sample number: 340000000000009 (15 digits)
   ================================================================ */

function isAmericanExpress(cc)
{
 firstdig = cc.substring(0,1);
 seconddig = cc.substring(1,2);
 if ((cc.length == 15) && (firstdig == 3) &&
     ((seconddig == 4) || (seconddig == 7)))
   return isCreditCard(cc);
 return false;

} // END FUNCTION isAmericanExpress()

/*  ================================================================
   FUNCTION:  isDiscover()

   INPUT:     cc - a string representing a credit card number

   RETURNS:  true, if the credit card number is a valid Discover number.

          false, otherwise

   Sample number: 6011 0000 0000 0004 (16 digits)
   ================================================================ */

function isDiscover(cc)
{
  first4digs = cc.substring(0,4);
  if ((cc.length == 16) && (first4digs == "6011"))
    return isCreditCard(cc);
  return false;

} // END FUNCTION isDiscover()


function isCardMatch (cardType, cardNumber)
{

    cardType = cardType.toUpperCase();
     //alert(cardType); 
    var doesMatch = true;
	

    if ((cardType == "VISA") && (!isVisa(cardNumber)))
        doesMatch = false;
    if ((cardType == "MASTERCARD") && (!isMasterCard(cardNumber)))
        doesMatch = false;
	if ((cardType == "DISCOVER") && (!isDiscover(cardNumber))) 
	doesMatch = false;
    if ( ( (cardType == "AMERICANEXPRESS") || (cardType == "AMEX") )
               && (!isAmericanExpress(cardNumber))) doesMatch = false;
    
	
	
	return doesMatch;

}  // END FUNCTION CardMatch()