var radiobutton="";
var reEmail = /^.+\@.+\..+$/;
var whitespace = " \t\n\r";
var phoneNumberDelimiters = "+()- ";
var numberDelimiters = "-";
var reInteger = /^\d+$/;
var payment = "no";

function checkFields(input)
{
   //alert("In checkFields");
    // Names des Feldes
    var requiredFields = new Array("name",
                                   "address",
                                   "country",
                                   "email",
                                   "payment_method");
    // Ausgabetext für die Fehlermeldung
    var fieldNames = new Array("Name",
                               "Straße, Hausnummer",
                               "Land, PLZ, Stadt",
                               "E-mail",
                               "Zahlungsart");

    // YOU SHOULD NOT NEED TO MAKE ANY CHANGES BELOW THIS POINT ------
    var fieldCheck   = true;
    var fieldValid   = true;
    var fieldsNeeded = "Folgende Felder müssen noch ausgefüllt werden:\n\t";
    var fieldsWrong = "Folgende Eingaben sind nicht korrekt:\n\t";

    for(var fieldNum=0; fieldNum < requiredFields.length; fieldNum++) {
        if ((input.elements[requiredFields[fieldNum]].value == "") ||
            (input.elements[requiredFields[fieldNum]].value == " ")) {
                    fieldsNeeded += fieldNames[fieldNum] + "\n\t";
                                 if (fieldCheck   ==  true) {
                                        fieldCheck = false;
                            input.elements[requiredFields[fieldNum]].focus();
                                }
        }
    }

    if (input.name.value!="" && input.name.value.length < 2) {
                fieldsWrong += "Name \""+input.name.value+"\"" + "\n\t";
                fieldValid=false;
        }

    if (input.address.value!="" && input.address.value.length < 2) {
                fieldsWrong += "Straße, Hausnummer \""+input.address.value+"\"" + "\n\t";
                fieldValid=false;
        }

    if (input.country.value!="" && input.country.value.length < 2) {
                fieldsWrong += "Land, PLZ, Stadt \""+input.country.value+"\"" + "\n\t";
                fieldValid=false;
        }

    if (input.email.value!="" && input.email.value.length < 2) {
                fieldsWrong += "E-mail \""+input.email.value+"\"" + "\n\t";
                fieldValid=false;
        }

    if (input.payment_method.value=="bank_todo" ) {
		// if second form
		payment="bank_todo";
	}
    else {
		// if fist form
	    if (input.payment_method[0].checked ==true ) {
			payment="bank_done";
		}
	    else if (input.payment_method[1].checked ==true ) {
			payment="bank_todo";
		}
	    else if (input.payment_method[2].checked ==true ) {
			payment="invoice";
		}
	    else if (input.payment_method[3].checked ==true ) {
			payment="creditcard";
		}
		else {
			fieldsNeeded += "Zahlungsart" + "\n\t";
			fieldCheck= false;
		}
	}

    // Test auf Kreditkarte und Land
    if (payment=="creditcard" && input.country.value.indexOf("Deutschland") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in Deutschland" + "\n\t";
                fieldValid=false;
        }
    if (payment=="creditcard" && input.country.value.indexOf("deutschland") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in Deutschland" + "\n\t";
                fieldValid=false;
        }
    if (payment=="creditcard" && input.country.value.indexOf("Österreich") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in Österreich" + "\n\t";
                fieldValid=false;
        }
    if (payment=="creditcard" && input.country.value.indexOf("österreich") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in Österreich" + "\n\t";
                fieldValid=false;
        }
    if (payment=="creditcard" && input.country.value.indexOf("Schweiz") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in der Schweiz" + "\n\t";
                fieldValid=false;
        }
    if (payment=="creditcard" && input.country.value.indexOf("schweiz") != -1) {
                fieldsWrong += "Keine Kreditkartenzahlung möglich in der Schweiz" + "\n\t";
                fieldValid=false;
        }

    if (payment=="creditcard") {
		if (input.creditcard[0].checked ==true ) {
			var card_no=stripWhitespace(input.creditcard_no.value);
			if (card_no != "") {
				if (!isMasterCard(card_no)) {
					fieldsWrong += "Kartennummer \""+input.creditcard_no.value+"\"" + "\n\t";
					fieldValid=false;
				}
			}
		}

		else if (input.creditcard[1].checked == true) {
			var card_no=stripWhitespace(input.creditcard_no.value);
			if (input.creditcard_no.value != "" && input.creditcard_no.value != " " ) {
				if (!isVisa(card_no)) {
					fieldsWrong += "Kartennummer \""+input.creditcard_no.value+"\"" + "\n\t";
					fieldValid=false;
				}
			}
		}

		else {
			fieldsNeeded += "Art der Kreditkarte" + "\n\t";
			fieldCheck= false;
		}


		if (input.creditcard_no.value=="" || input.creditcard_no.value==" ") {
			fieldsNeeded += "Kartennummer" + "\n\t";
			fieldCheck= false;
		}
		if (input.creditcard_valid.value!="" && input.creditcard_valid.value!=" "){

			var month=get_month(input.creditcard_valid.value);
			var year=get_year(input.creditcard_valid.value);
			//alert(month);
			//alert(year);
			var expiry_date=true;
			today = new Date();
			expiry = new Date(year, month);
			//if (today.getTime() > expiry.getTime())
			//     expiry_date= false;
			if  (!isIntegerInRange(month,1,12) ||
				(!isIntegerInRange(year,1,12) &&
			    !isIntegerInRange(year,2008,2020)))
		        expiry_date= false;
			if  (!expiry_date) {
					fieldsWrong +=
					"gültig bis (\"MM/JJ\") \""+input.creditcard_valid.value+
					"\"" + "\n\t";
					fieldValid=false;
	        }
        }
		else {
			fieldsNeeded += "gültig bis (MM/JJ)" + "\n\t";
			fieldCheck= false;
		}
    }
    if (payment=="bank_todo") {
		if (input.bank_institut.value=="" || input.bank_institut.value==" ") {
			fieldsNeeded += "Kreditinstitut" + "\n\t";
			fieldCheck= false;
		}
		var bank_blz=stripWhitespace(input.bank_blz.value);
		bank_blz=stripNumberDelimiters(bank_blz);

		if (bank_blz=="" || bank_blz==" ") {
			fieldsNeeded += "Bankleitzahl" + "\n\t";
			fieldCheck= false;
		}
		else {
			if (!isInteger(bank_blz) || bank_blz.length!=8) {
				fieldsWrong +=
				"Bankleitzahl \""+input.bank_blz.value+"\"" + "\n\t";
				fieldValid=false;
			}
		}
		var bank_conto=stripWhitespace(input.bank_conto.value);
		bank_conto=stripNumberDelimiters(bank_conto);
		if (bank_conto=="" || bank_conto==" ") {
			fieldsNeeded += "Kontonummer" + "\n\t";
			fieldCheck= false;
		}
		else {
			if (!isInteger(bank_conto)) {
				fieldsWrong +=
				"Kontonummer \""+input.bank_conto.value+"\"" + "\n\t";
				fieldValid=false;
			}
		}
	}
    // ALL REQUIRED FIELDS HAVE BEEN ENTERED
    if (fieldCheck == true && fieldValid==true)
    {
        return (true);
    }
    // SOME REQUIRED FIELDS ARE MISSING VALUES
    else
    {
        if (fieldCheck==false) {
                        fieldsOut=fieldsNeeded;
                }
        if (fieldValid==false) {
                if (fieldCheck==false) {fieldsOut+="\n\n";}
                else {fieldsOut="";}
                fieldsOut+=fieldsWrong;
        }
        alert(fieldsOut);
        return (false);
    }
}

/*  ================================================================
    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 true;
        return isCreditCard(cc);
        return false;
        //alert(cc);

}

//  ================================================================
//    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 true;

        return isCreditCard(cc);
        }
        //alert(cc);
  return false;
}  // END FUNCTION isVisa()



/*  ================================================================
    FUNCTION:  isCreditCard(st)

    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
                    test.
              false, otherwise
    ================================================================
*/
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++;
      // Multiplikator 2
    else
      mul--;
      // Multiplikator 1
  }
// 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()



// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{
        //alert(s);
        return reEmail.test(s);
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s)

{   return stripCharsInBag (s, whitespace)
}

function stripNumberDelimiters (s)

{   return stripCharsInBag (s, numberDelimiters)
}


// Removes all characters which appear in string bag from string s.

function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    //alert(returnString);
        return returnString;
}


function isIntegerInRange (s, a, b)
{
    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if (!isInteger(s, false)) return false;

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = makeInt (s);
    //alert(num);
    return ((num >= a) && (num <= b));
}

function isInteger (s)
{
    return reInteger.test(s)

}

function get_month(s)
{
    var month="";
    for (i = 0; i < s.length; i++) {
        var c=s.charAt(i);
        if (c=="/" || c=="-"  || c==" ")
            return month;
        if (c!="0") month+=c;
    }

}


function get_year(s)
{
    var year="";
    var add_year="";
    for (i = 0; i < s.length; i++) {
        var c=s.charAt(i);
        if (add_year=="yes") year+=c;
        if (c=="/" || c=="-" || c==" ")
            add_year="yes";
    }
    if (year.length==2) year="20"+year;
    if (year.length==1) year="200"+year;
    //alert (year);
    return year;
}


function makeInt (s)
{
        if (s == "01") return "1";
        else if (s=="02") return "2";
        else if (s=="03") return "3";
        else if (s=="04") return "4";
        else if (s=="05") return "5";
        else if (s=="06") return "6";
        else if (s=="07") return "7";
        else if (s=="08") return "8";
        else if (s=="09") return "9";
        else return s;
}
