/* TO DO: PUT ALL JAVASCRIPT IN A .JS FILE AND INCLUDE IT IN ALL HEADERS*/

//*************************************************************************
//THESE FUNCTIONS TAKE IN A VARIABLE TO DISTINGUISH WHETHER
//THE FUNCTION HAVE TO WORK ACROSS FRAMES
var form='frmcartype' //Give the form name here

function SetChecked(val,chkName) {
  dml=document.forms[form];
  len = dml.elements.length;
  var i=0;
  for( i=0 ; i<len ; i++) {
    if (dml.elements[i].name==chkName) {
      dml.elements[i].checked=val;
    }
  }
}

function ValidateForm(dml,chkName){
  len = dml.elements.length;
  var i=0;
  for( i=0 ; i<len ; i++) {
    if ((dml.elements[i].name==chkName) && (dml.elements[i].checked==1)) return true
  }
  alert("Please select at least one record for deletion.")
  return false;
}

function selectAll(Frames)
{
	if(Frames == true)
	{
		for(i=0; i < parent.display.mainform.length; i++)
		{
			parent.display.mainform.elements[i].checked=true;
		}
	}
	else
	{
		for(i=0; i < document.mainform.length; i++)
		{
			document.mainform.elements[i].checked=true;
		}
	}

}
function setBookDate(myday, mymonth, myyear) {
  var currentDate ;
  if (myday != '') {
    currentDate = new Date(myyear, mymonth-1, myday) ;
  }
  else {
    currentDate = new Date() ;
  }
  // Check to see if the Form dateForm  exists.
  if (typeof(document.Frmbook) != "undefined")	{
    // If the From dateFrom does exist then check to see if the inyear field exists
    if (typeof(document.Frmbook.bookyear) != "undefined") {
	  // If the inyear field exists then set the year = to the first element in the drop down
	  for (var i = 0 ; i < 8; i++){
	    if (document.Frmbook.bookyear.options[i].text == myyear) {
		  document.Frmbook.bookyear.options[i].selected = true ;
		}
	  }
      //document.dateForm.pickupyear.selectedIndex = 0;
	  // Set the month equal to the month from the current time
      document.Frmbook.bookmonth.selectedIndex = currentDate.getMonth();
	  // Call the set days function to see how many days the particular month has an set them.
      setBookDays();

	  if (myday != '') {
        document.Frmbook.bookday.selectedIndex = currentDate.getDate() - 1 ;
      }
      else {
        document.Frmbook.bookday.selectedIndex = currentDate.getDate() - 1 ;
      }
	}
  }
}
// Function to Set the current month and day for the selection boxes.
function setPickUpDate(myday, mymonth, myyear) {
  var currentDate ;
  if (myday != '') {
    currentDate = new Date(myyear, mymonth-1, myday) ;
  }
  else {
    currentDate = new Date() ;
  }
  // Check to see if the Form dateForm  exists.
  if (typeof(document.dateForm) != "undefined")	{
    // If the From dateFrom does exist then check to see if the inyear field exists
    if (typeof(document.dateForm.pickupyear) != "undefined") {
	  // If the inyear field exists then set the year = to the first element in the drop down
	  for (var i = 0 ; i < 8; i++){
	    if (document.dateForm.pickupyear.options[i].text == myyear) {
		  document.dateForm.pickupyear.options[i].selected = true ;
		}
	  }
      //document.dateForm.pickupyear.selectedIndex = 0;
	  // Set the month equal to the month from the current time
      document.dateForm.pickupmonth.selectedIndex = currentDate.getMonth();
	  // Call the set days function to see how many days the particular month has an set them.
      setPickUpDays();

	  if (myday != '') {
        document.dateForm.pickupday.selectedIndex = currentDate.getDate() - 1 ;
      }
      else {
        document.dateForm.pickupday.selectedIndex = currentDate.getDate() + 2 ;
      }
	}
  }
}

// Function to Set the current month and day for the selection boxes.
function setDropOffDate(myday, mymonth, myyear) {
  var currentDate ;
  if (myday != '') {
    currentDate = new Date(myyear, mymonth-1, myday) ;
  }
  else {
    currentDate = new Date() ;
  }
  // Check to see if the Form dateForm  exists.
  if (typeof(document.dateForm) != "undefined")	{
    // If the From dateFrom does exist then check to see if the inyear field exists
    if (typeof(document.dateForm.dropoffyear) != "undefined") {
	  // If the inyear field exists then set the year = to the first element in the drop down
	  for (var i = 0 ; i < 8; i++){
	    if (document.dateForm.dropoffyear.options[i].text == myyear) {
		  document.dateForm.dropoffyear.options[i].selected = true ;
		}
	  }
	  //document.dateForm.dropoffyear.selectedIndex = 0 ;
	  // Set the month equal to the month from the current time
      document.dateForm.dropoffmonth.selectedIndex = currentDate.getMonth();
	  // Call the set days function to see how many days the particular month has an set them.
      setDropOffDays();
	  if (myday != '') {
        document.dateForm.dropoffday.selectedIndex = currentDate.getDate() - 1 ;
      }
      else {
        document.dateForm.dropoffday.selectedIndex = currentDate.getDate() + 5 ;
      }

	}
  }
}
function setBookDays() {
  var y = document.Frmbook.bookyear.options[document.Frmbook.bookyear.selectedIndex].value;
  var m = document.Frmbook.bookmonth.selectedIndex;
  var d;
  if ( (m == 3) || (m == 5) || (m == 8) || (m == 10) ) {
    days = 30;
  }
  else if (m == 1) {
    if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
      days = 29
    else
      days = 28
  }
  else {
    days = 31;
  }

  if (days > document.Frmbook.bookday.length) {
    for (i = document.Frmbook.bookday.length; i < days; i++) {
      document.Frmbook.bookday.length = days;
      document.Frmbook.bookday.options[i].text = i + 1;
      document.Frmbook.bookday.options[i].value = i + 1;
    }
  }

  if (days < document.Frmbook.bookday.length) {
    document.Frmbook.bookday.length = days;
    if (document.Frmbook.bookday.selectedIndex == -1)
      document.Frmbook.bookday.selectedIndex = days - 1;
  }
}
function setPickUpDays() {
  var y = document.dateForm.pickupyear.options[document.dateForm.pickupyear.selectedIndex].value;
  var m = document.dateForm.pickupmonth.selectedIndex;
  var d;
  if ( (m == 3) || (m == 5) || (m == 8) || (m == 10) ) {
    days = 30;
  }
  else if (m == 1) {
    if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
      days = 29
    else
      days = 28
  }
  else {
    days = 31;
  }

  if (days > document.dateForm.pickupday.length) {
    for (i = document.dateForm.pickupday.length; i < days; i++) {
      document.dateForm.pickupday.length = days;
      document.dateForm.pickupday.options[i].text = i + 1;
      document.dateForm.pickupday.options[i].value = i + 1;
    }
  }

  if (days < document.dateForm.pickupday.length) {
    document.dateForm.pickupday.length = days;
    if (document.dateForm.pickupday.selectedIndex == -1)
      document.dateForm.pickupday.selectedIndex = days - 1;
  }
}
function setDropOffDays() {
  var y = document.dateForm.dropoffyear.options[document.dateForm.dropoffyear.selectedIndex].value;
  var m = document.dateForm.dropoffmonth.selectedIndex;
  var d;
  if ( (m == 3) || (m == 5) || (m == 8) || (m == 10) ) {
    days = 30;
  }
  else if (m == 1) {
    if ( (Math.floor(y/4) == (y/4)) && ((Math.floor(y/100) != (y/100)) || (Math.floor(y/400) == (y/400))) )
      days = 29
    else
      days = 28
  }
  else {
    days = 31;
  }

  if (days > document.dateForm.dropoffday.length) {
    for (i = document.dateForm.dropoffday.length; i < days; i++) {
      document.dateForm.dropoffday.length = days;
      document.dateForm.dropoffday.options[i].text = i + 1;
      document.dateForm.dropoffday.options[i].value = i + 1;
    }
  }

  if (days < document.dateForm.dropoffday.length) {
    document.dateForm.dropoffday.length = days;
    if (document.dateForm.dropoffday.selectedIndex == -1)
      document.dateForm.dropoffday.selectedIndex = days - 1;
  }
}
function showTable(TableDetails,Frm)
{
  if (document.getElementById(TableDetails).style.display == 'none')
  {
	document.getElementById(TableDetails).style.display = 'block';
	document.getElementById(Frm).elements[0].focus() ;
  }
  else
  {
	document.getElementById(TableDetails).style.display = 'none';
  }
}

var lastSelected = null ;

function ShowCarTd(Val) {

  if (lastSelected != null) {
    document.getElementById('TD'+lastSelected).style.display = 'none';
  }
  //ar inserted
  if (document.getElementById('TD'+Val) !=null)
  {
  //ends
  if (document.getElementById('TD'+Val).style.display == 'none')
  {
	document.getElementById('TD'+Val).style.display = 'block';
  }

  lastSelected = Val ;
  //ar inserted
  }
//ends
}

var CurrentTable = 1 ;
var NextTable ;

function IncrementMonth() {
  if (typeof(document.setavailability) != 'undefined') {
    NextTable = CurrentTable + 1 ;
    if (NextTable > 12) {
      NextTable = 1 ;
    }
  }
}
function DecrementMonth() {
  if (typeof(document.setavailability) != 'undefined') {
    NextTable = CurrentTable - 1 ;
    if (NextTable < 1) {
      NextTable = 12 ;
    }
  }
}

function ChangeMonth() {
  if (typeof(document.setavailability) != 'undefined') {

    if (document.getElementById('T'+CurrentTable).style.display == 'block') {
	  document.getElementById('T'+CurrentTable).style.display = 'none';
    }
    if (document.getElementById('T'+NextTable).style.display == 'none') {
	  document.getElementById('T'+NextTable).style.display = 'block';
    }
    CurrentTable = NextTable ;
  }
}

function isChar(strString) {
  var strValidChars = "ABCEDFXS" ;
  var strChar ;
  var blnResult = true ;

  if (strString.length == 0) return false ;

  for (i = 0; i < strString.length && blnResult == true; i++) {
    strChar = strString.charAt(i) ;
    if (strValidChars.indexOf(strChar) == -1) {
         blnResult = false ;
    }
  }
  return blnResult ;
}

function isChar1(strString) {
  var strValidChars = "HLM" ;
  var strChar ;
  var blnResult = true ;

  if (strString.length == 0) return false ;

  for (i = 0; i < strString.length && blnResult == true; i++) {
    strChar = strString.charAt(i) ;
    if (strValidChars.indexOf(strChar) == -1) {
         blnResult = false ;
    }
  }
  return blnResult ;
}

function ValidateText1(elem) {
  if ((elem.value==null)||(elem.value=="")) {
    alert("You have not entered price structure. Please Enter a valid price structure.") ;
    elem.focus() ;
	return false ;
  }
  else if (!isChar1(elem.value)) {
	alert("You have not entered a valid price structure.\nPlease make sure you enter a charachter value only.\n\nCorrect values are in the range H , M and L. \n\n Please Enter a valid price structure charachter.") ;
	elem.focus() ;
	return false ;
  }
  return true ;
}

function submitForm(formName, iSubmitType)
{
  if(iSubmitType == '1')
  {
    if (confirm("Are you sure you wish to update this record?") == true)
	{
	  formName.Transaction.value = "Update";
	  formName.submit();
	}
  }
  else if(iSubmitType == '2')
  {
    if (confirm("Are you sure you wish to delete this record?") == true)
	{
	  formName.Transaction.value = "Delete";
	  formName.submit();
	}
  }
}

function AddTrader(FormId)
{
  document.getElementById(FormId).submit() ;
}
function checkChoices()
{
	/*carType
	collectDay
	collectMonth
	collectYear
	returnDay
	returnMonth
	returnYear
	collectLocation
	returnLocation*/
	var test = true;
	today = new Date();
	collectDay = dateForm.pickupday.value;
	collectMonth = dateForm.pickupmonth.value;
	collectYear = dateForm.pickupyear.value;
	returnDay = dateForm.dropoffday.value;
	returnMonth = dateForm.dropoffmonth.value;
	returnYear = dateForm.dropoffyear.value;
	if( dateForm.carType.value == "" )
	{
		test = false;
		//mainform.carType.setFocus();
		alert("You must choose a Car Type");
		return test;
	}
	else
	{
		if( checkDateAgainstToday(collectDay,collectMonth,collectYear) )
		{
			 if( checkDate(collectDay,collectMonth,collectYear,returnDay,returnMonth,returnYear) )
			{
				if(dateForm.pickuplocation.value=="")
				{
					test = false;
					//mainform.collectLocation.setFocus();
					alert("You must choose a Location to Collect the Car");
					return test;
				}
				if(dateForm.dropofflocation.value=="")
				{
					test = false;
					//mainform.collectLocation.setFocus();
					alert("You must choose a Location to Return the Car");
					return test;
				}
			}
			else
			{
				test = false;
				return test;
			}

		}
		else
		{
			test = false;
			//mainform.collectDay.setFocus();
			return test;
		}


	}
	return test;
}

function checkDateAgainstToday(day, month, year)
{
	today = new Date();
	var test = true;
	if( today.getYear()  > year )
	{
		test = false;
		alert("The Selected Year has Passed!");
		return test;
	}
	if( ((today.getMonth() + 1)  > month) && (today.getYear()  == year ))
	{
		test = false;
		alert("The Selected Month has passed!");
		return test;
	}
	if( (today.getDate()  > day) && (today.getYear()  == year ) && (today.getMonth() + 1  == month )  )
	{
		test = false;
		alert("The Selected Date has passed!");
		return test;
	}
	return test;
}
function checkDate(day, month, year,returnDay,returnMonth,returnYear)
{
	var test=true;
	returnMonth = parseInt(returnMonth);
	month =  parseInt(month);
	//returnDay = parseInt( returnDay);
	//day =  parseInt(day);
	returnYear =  parseInt(returnYear);
	year =  parseInt(year);
	if( year > returnYear )
	{
		test = false;
		alert("The Return Year is before Collection Year!");
		return test;
	}
	return test;
}
function OpenCertDetails()
{
	thewindow = window.open('https://www.thawte.com/cgi/server/certdetails.exe?code=IEATLA2', 'anew', config='height=511,width=516,toolbar=no,menubar=no,scrollbars=yes,resizable=no,location=no,directories=no,status=yes');
}

/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   interger  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor) {

    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined' && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function



function resetForm(Frames)
{
	if(Frames == true)
	{
		for(i=0; i < parent.display.mainform.length; i++)
		{
			parent.display.mainform.elements[i].checked=false;
		}
	}
	else
	{
		for(i=0; i < document.mainform.length; i++)
		{
			document.mainform.elements[i].checked=false;
		}
	}
}
//******************************************************************
function showQuery(strQuery)
{
	var loc = new String("./cars.php?q=" + strQuery);
	window.opener.document.location.href=loc;
	window.close();
}


function popUpUrl(URL)
{
		var dest = URL;
		winpops=window.open(URL,"",'width=520,height=585,scrollbars=yes,resizable=no,menubar=no,status=no,toolbar=no');
}

function opencalc(priceOfCar)
{
		var popupurl ="../FinanceCalc/aprcalc.php?price=" + priceOfCar ;
		winpops=window.open(popupurl,"",'width=400, height=480');
}

function choose(button)
{
		if( button == "Add")
		{
			mainform.action.value = "Add";
		}
		if( button == "Modify" )
		{
			mainform.action.value = "Modify";
		}
		if( button == "Remove" )
		{
			mainform.action.value = "Remove";
		}

		mainform.submit();
}

function change()
{
	var index = parent.choice.mainform.carType.value;
	if( index == 0 )
	{
		var url = "display.php";
	}
	else
	{
		var url = "display.php?type_id=" + index;
	}
	top.display.location.href=url;
}
function checkifdateselected() {
  var terms = document.Frmbook.usebookdate.checked ;
  if (terms == false) {

var terms2 = document.Frmbook.plus_minus_days.checked ;
  if (terms2 == false) {
    document.Frmbook.bookday.value = "" ;
	document.Frmbook.bookmonth.value = "" ;
	document.Frmbook.bookyear.value = "" ;
  }
  }


}
function testPay() {
	var test = true ;
	var card_number = document.frmmain.credit_card_number.value ;
	var CardType = document.frmmain.cardtype.value ;
	var Month = document.frmmain.Month.value ;
	var Year = document.frmmain.Year.value ;
	var name = document.frmmain.realname.value ;
	var address = document.frmmain.address.value ;
	var occupation = document.frmmain.occupation.value ;
	var telephone = document.frmmain.tele.value ;
    var terms = document.frmmain.terms.checked ;

    var country= document.getElementById("country").options[document.getElementById("country").selectedIndex].value ;
   if (country == "") {
		alert("Please enter your country of origin");
		 document.getElementById("country").focus();
		return false;
	}

    var problem = check_where_you();
	//alert("HERE");
	if(problem ==false)
	{
	document.getElementById("find_us_other").focus();
	return false;
	}
	if (name == "") {
		alert("Please enter your Name");
		document.frmmain.realname.focus();
		return false;
	}
	if (address == "")	{
		alert("Please enter your Address");
		document.frmmain.address.focus();
		return false;
	}
	if (occupation == "") {
		alert("Please enter your Occupation");
		document.frmmain.occupation.focus();
		return false;
	}
	if (telephone == "") {
		alert("Please enter your Telephone Number");
		document.frmmain.tele.focus();
		return false;
	}
    if (terms == false) {
		alert("Please read the terms and conditions and then check the checkbox.");
		return false;
	}
	if(validate_email())
	{
		if( validateCard(card_number,CardType,Month,Year) )
		{
			//alert("Card Is Valid");
		}
		else
		{
			alert("Card Is inValid");
			test = false;
		}

	}
	else
	{
		test = false;
	}
	return test;
}

function validate_email()
{
	indexofAt = frmmain.email.value.indexOf('@',0);
	indexofDot = frmmain.email.value.lastIndexOf('.',frmmain.email.value.length -1);
	var test = true;
	if (indexofAt == 0 || indexofAt == -1)
	{
		alert("Please enter a valid E-mail Address");
		document.frmmain.email.focus();
		test = false;
	}
	else
	{
		if( indexofDot < indexofAt || indexofDot == -1 )
		{
			alert("Please enter a valid E-mail Address");
			document.frmmain.email.focus();
			test =  false;
		}
		else
		{
			test =  true;
		}
	}
	return test;
}


/**********************************************************************************
***********************************************************************************
*********			   CREDIT CARD VALIDATION FUNCTIONS					***********
***********************************************************************************
**********************************************************************************/

//
// Name: Credit Card Validator
// Description:These functions thoroughl
//     y attempt to invalidate American Express
//     , Discover, MasterCard and Visa with len
//     gth, character validation, prefix matchi
//     ng, check digit, and expiration date tes
//     ts. The html test document by no means w
//     ill attempt to forward your credit card
//     numbers. The action of the form is set t
//     o an invalid URL
// By: vsim
//
//This code is copyrighted and has// limited warranties.Please see http://
//     www.Planet-Source-Code.com/xq/ASP/txtCod
//     eId.2493/lngWId.2/qx/vb/scripts/ShowCode
//     .htm//for details.//**************************************
//

/*
There are three functions in this set for credit card validation.
The main function is:
validateCard(cardNumber,cardType,cardMonth,cardYear)
	parameters:
		all paramaters are string values.
		Month & Year come from the select input fields in the form, so they are defined.
		cardType can be:
			'a' for American Express
			'd' for Discover
			'm' for MasterCard
			'v' for Visa
	description:
		this function will check string length, valid characters, specific credit card prefixes and test
		the Mod 10 (LUHN Formula) for validating possible credit card numbers. this function can only
		authorize that the given card data is potentially valid. You would still need to run actual
		card validation routines to verify the actual account.
	returns:
		this function returns true if the card number could be valid for the card type and expiration date.
		false otherwise.
supporting functions:
mod10( cardNumber )
	parameters:
		this function takes the text string card number and runs the Mod 10 formula on its respective digits.
	description:
		Mod 10 is the check digit formula for the supported cards these functions attempt to validate.
	returns:
		this function returns true if the number passes the check digit test.
		false otherwise.
expired( cardMonth, cardYear )
	parameters:
		this function takes the text string values given by the html form.
	description:
		this function basically will check to make sure todays date is less than the expiration date the user inputs.
		this function is not locked into using 2 digit dates.
	returns:
		this fucntion returns true if the card is expired.
		false otherwise.
*/
function mod10( cardNumber ) { // LUHN Formula for validation of credit card numbers.
	var ar = new Array( cardNumber.length );
	var i = 0,sum = 0;


    	for( i = 0; i < cardNumber.length; ++i ) {
    		ar[i] = parseInt(cardNumber.charAt(i));
    	}
    	for( i = ar.length -2; i >= 0; i-=2 ) { // you have to start from the right, and work back.
    		ar[i] *= 2;							 // every second digit starting with the right most (check digit)
    		if( ar[i] > 9 ) ar[i]-=9;			 // will be doubled, and summed with the skipped digits.
    	}										 // if the double digit is > 9, ADD those individual digits together


        	for( i = 0; i < ar.length; ++i ) {
        		sum += ar[i];						 // if the sum is divisible by 10 mod10 succeeds
        	}
        	return (((sum%10)==0)?true:false);
    }

 function expired( month, year )
{
        	var now = new Date();							// this function is designed to be Y2K compliant.
        	var expiresIn = new Date(year,month,0,0,0);		// create an expired on date object with valid thru expiration date
        	expiresIn.setMonth(expiresIn.getMonth()+1);		// adjust the month, to first day, hour, minute & second of expired month
        	if( now.getTime() < expiresIn.getTime() )
			{
				return false;
			}
        	return true;									// then we get the miliseconds, and do a long integer comparison
    }


function validateCard(cardNumber,cardType,cardMonth,cardYear)
{
    if( cardNumber.length == 0 )
	{						//most of these checks are self explanitory
    	alert("Please enter a valid card number.");
    	return false;
    }
    for( var i = 0; i < cardNumber.length; ++i )
	{		// make sure the number is all digits.. (by design)

		var c = cardNumber.charAt(i);
		if( c < '0' || c > '9' )
		{
            	alert("Please enter a valid card number. Use only digits. do not use spaces or hyphens.");
            	return false;
        }
    }
    var length = cardNumber.length;			//perform card specific length and prefix tests


    switch( cardType )
	{
        case 'a':
		if( length != 15 )
		{
            alert("Please enter a valid American Express Card number.");
            return;
        }
        var prefix = parseInt( cardNumber.substring(0,2));
		if( prefix != 34 && prefix != 37 )
		{
			alert("Please enter a valid American Express Card number.");
			return;
		}
		break;

		case 'd':
		if( length != 16 )
		{
			alert("Please enter a valid Discover Card number.");
			return;
		}
		var prefix = parseInt( cardNumber.substring(0,4));
		if( prefix != 6011 )
		{
			alert("Please enter a valid Discover Card number.");
			return;
		}
		break;

		case 'm':
		if( length != 16 )
		{
			alert("Please enter a valid MasterCard number.");
			return;
		}
		var prefix = parseInt( cardNumber.substring(0,2));
		if( prefix < 51 || prefix > 55)
		{
			alert("Please enter a valid MasterCard Card number.");
			return;
		}
		break;

		case 'v':
		if( length != 16 && length != 13 )
		{
			alert("Please enter a valid Visa Card number.");
			return;
		}
		var prefix = parseInt( cardNumber.substring(0,1));


		if( prefix != 4 )
		{
			alert("Please enter a valid Visa Card number.");
			return;
		}
		break;
}
if( !mod10( cardNumber ) )
{ 		// run the check digit algorithm
	alert("Sorry! this is not a valid credit card number.");
	return false;
}
if( expired( cardMonth, cardYear ) )
{							// check if entered date is already expired.
	alert("Sorry! The expiration date you have entered would make this card invalid.");
	return false;
}

return true; // at this point card has not been proven to be invalid

}
