/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */
// checkAddress (TEXTFIELD theField, STRING s [, BOOLEAN required==true])
// checkCheckBoxes (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
// checkDate (TEXTFIELD yearField, TEXTFIELD monthField, TEXTFIELD dayField, STRING sMessage [, BOOLEAN required==true, BOOLEAN OKtoOmitDay==false])
// checkEmail (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
// checkMonth (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
// checkPhoneNumber (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
// checkRadioButtons (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
// checkString (TEXTFIELD theField, STRING s, INTEGER type [, BOOLEAN required==true])
// checkYear (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])


// VARIABLE DECLARATIONS
var Digits = "0123456789";
var Letters = "abcçdefgğhıijklmnoöpqrsştuüvwxyzABCÇDEFGĞHIİJKLMNOÖPQRSŞTUÜVWXYZ ";

// whitespace characters
var whitespace = " \t\n\r";

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// characters which are allowed in international phone numbers
// (a leading + is OK)
var validPhoneChars = Digits + phoneNumberDelimiters + "+";

// characters which are allowed in international phone numbers
// (a leading + is OK)
var validAddressChars = Digits + Letters + ".:,/\\()- ";

var defaultEmptyOK = false;

// String Check Type Constants
var Numeric = 0;
var Alphabetic = 1;
var AlphaNumeric = 2;
var Address = 3;


// CONSTANT STRING DECLARATIONS

// m is an abbreviation for "missing"
var mPrefix = "Lütfen ";
var mSuffix = " sahasına bilgi giriniz.";

// i is an abbreviation for "invalid"
var iPhone = "Bu sahaya maksimum 10 rakamdan oluşan bir telefon numarası girmeniz gerekiyor. (örneğin (212) 1234567).\nLütfen tekrar kontrol ediniz."
var iEmail = "Bu sahaya doğru formatta email adresi girmeniz gerekiyor. (örneğin ornek@test.com.tr).\nLütfen tekrar kontrol ediniz.";
var iNumeric = "Bu sahaya sadece rakamlardan oluşan bilgi girebilirsiniz.\nLütfen tekrar kontrol ediniz.";
var iAlphabetic = "Bu sahaya sadece harflerden oluşan bilgi girebilirsiniz.\nLütfen tekrar kontrol ediniz.";
var iAlphanumeric = "Bu sahaya sadece harf ve rakamlardan oluşan bilgi girebilirsiniz.\nLütfen tekrar kontrol ediniz.";

var iAddress = "Bu sahaya sadece harf, rakam ve '.:,/\()-' özel işaretlerinden oluşan bilgi girebilirsiniz.\nLütfen tekrar kontrol ediniz.";
var iDay = "Bu sahaya 1 ile 31 rakamları arasında gün bilgisi girmeniz gerekiyor.\nLütfen tekrar kontrol ediniz.";
var iMonth = "Bu sahaya 1 ile 12 rakamları arasında ay bilgisi girmeniz gerekiyor.\nLütfen tekrar kontrol ediniz.";
var iYear = "Bu sahaya 2 veya 4 basamaklı yıl bilgisi girmeniz gerekiyor.\nLütfen tekrar kontrol ediniz.";
var iDatePrefix = "Girmiş olduğunuz ";
var iDateSuffix = " tarihi geçerli bir tarih değildir.\nLütfen tekrar kontrol ediniz.";
var iRadioSuffix = " grubundaki seçeneklerden bir tanesini seçmeniz gerekiyor.\nLütfen tekrar kontrol ediniz.";
var iCheckBoxSuffix = " grubundaki seçeneklerden en az bir tanesini seçmeniz gerekiyor.\nLütfen tekrar kontrol ediniz.";


function makeArray (n)
{
  for (var i = 1; i <= n; i++)
  {
    this[i] = 0
  } 
  return this
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;


// Check whether string s is empty.
function isEmpty (s)
{
  return ((s == null) || (s.length == 0));
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s)
{
  var i;

  // Is s empty?
  if (isEmpty(s)) return true;

  // Search through string's characters one by one
  // until we find a non-whitespace character.
  // When we do, return false; if we don't, return true.
  for (i = 0; i < s.length; i++)
  {   
    // Check that current character isn't whitespace.
    var c = s.charAt(i);

    if (whitespace.indexOf(c) == -1) return false;
  }

  // All characters are whitespace.
  return true;
}

// Removes all whitespace characters from s.
function stripWhitespace (s)
{
  var i;
  var returnString = "";

  // Is s empty?
  if (isEmpty(s)) return 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 (whitespace.indexOf(c) == -1) returnString += c;
  }

  return returnString;
}


// Returns true if character c is an English letter (A .. Z, a..z).
function isLetter (c)
{
  return ((Letters.indexOf(c) == -1) ? false : true);
}

// Returns true if character c is a digit (0 .. 9).
function isDigit (c)
{
  return ((Digits.indexOf(c) == -1) ? false : true);
}

// Returns true if character c is a letter or digit.
function isLetterOrDigit (c)
{
  return (isLetter(c) || isDigit(c));
}

// isInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if all characters in string sFieldValue are numbers.
//
// Accepts non-signed integers only. Does not accept floating 
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.

function isInteger (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isInteger.arguments.length == 1) return defaultEmptyOK;
    else return (!isInteger.arguments[1]);

  // Search through string's characters one by one
  // until we find a non-numeric character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < sFieldValue.length; i++)
  {   
    // Check that current character is number.
    var c = sFieldValue.charAt(i);

    if (!isDigit(c)) return false;
  }

  // All characters are numbers.
  return true;
}

// isSignedInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if all characters are numbers; 
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.

function isSignedInteger (sFieldValue)
{
  if (isWhitespace(sFieldValue))
    if (isInteger.arguments.length == 1) return defaultEmptyOK;
    else return (!isInteger.arguments[1]);
  else
  {
    var startPos = 0;
    var secondArg = defaultEmptyOK;

    if (isSignedInteger.arguments.length > 1)
      secondArg = isSignedInteger.arguments[1];

    // skip leading + or -
    if ( (sFieldValue.charAt(0) == "-") || (sFieldValue.charAt(0) == "+") )
      startPos = 1;

    return (isInteger(sFieldValue.substring(startPos, sFieldValue.length), secondArg));
  }
}

// isNonnegativeInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue is an integer >= 0.

function isNonnegativeInteger (sFieldValue)
{
  var secondArg = defaultEmptyOK;

  if (isNonnegativeInteger.arguments.length > 1)
    secondArg = isNonnegativeInteger.arguments[1];

  return (isSignedInteger(sFieldValue, secondArg)
          && ( (isEmpty(sFieldValue) && secondArg)  || (parseInt (sFieldValue) >= 0) ) );
}

// isNonpositiveInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue is an integer <= 0.

function isNonpositiveInteger (sFieldValue)
{
  var secondArg = defaultEmptyOK;

  if (isNonpositiveInteger.arguments.length > 1)
    secondArg = isNonpositiveInteger.arguments[1];

  return (isSignedInteger(sFieldValue, secondArg)
          && ( (isEmpty(sFieldValue) && secondArg)  || (parseInt (sFieldValue) <= 0) ) );
}

// isPositiveInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue is an integer > 0.

function isPositiveInteger (sFieldValue)
{
  var secondArg = defaultEmptyOK;

  if (isPositiveInteger.arguments.length > 1)
    secondArg = isPositiveInteger.arguments[1];

  return (isSignedInteger(sFieldValue, secondArg)
          && ( (isEmpty(sFieldValue) && secondArg)  || (parseInt (sFieldValue) > 0) ) );
}

// isNegativeInteger (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue is an integer < 0.

function isNegativeInteger (sFieldValue)
{
  var secondArg = defaultEmptyOK;

  if (isNegativeInteger.arguments.length > 1)
    secondArg = isNegativeInteger.arguments[1];

  return (isSignedInteger(sFieldValue, secondArg)
          && ( (isEmpty(sFieldValue) && secondArg)  || (parseInt (sFieldValue) < 0) ) );
}

// isIntegerInRange (STRING sFieldValue, INTEGER a, INTEGER b)
// 
// isIntegerInRange returns true if string sFieldValue is an integer 
// within the range of integer arguments a and b, inclusive.

function isIntegerInRange (sFieldValue, a, b, required)
{
  // Catch non-integer strings to avoid creating a NaN below,
  // which isn't available on JavaScript 1.0 for Windows.
  if (!isInteger(sFieldValue, 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 = parseInt (sFieldValue);
  return ((num >= a) && (num <= b));
}

// isYear (STRING s [, BOOLEAN emptyOK])
// 
// isYear returns true if string s is a valid 
// Year number.  Must be 2 or 4 digits only.

function isYear (s)
{
  if (isEmpty(s))
    if (isYear.arguments.length == 1) return defaultEmptyOK;
    else return (isYear.arguments[1] == true);

  if (!isNonnegativeInteger(s)) return false;

  return ((s.length == 2) || (s.length == 4));
}

// isMonth (STRING s [, BOOLEAN emptyOK])
// 
// isMonth returns true if string s is a valid 
// month number between 1 and 12.

function isMonth (s)
{
  if (isEmpty(s)) 
    if (isMonth.arguments.length == 1) return defaultEmptyOK;
    else return (isMonth.arguments[1] == true);
  return isIntegerInRange (s, 1, 12);
}

// isDay (STRING s [, BOOLEAN emptyOK])
// 
// isDay returns true if string s is a valid 
// day number between 1 and 31.

function isDay (s)
{
  if (isEmpty(s)) 
    if (isDay.arguments.length == 1) return defaultEmptyOK;
    else return (isDay.arguments[1] == true);   
  return isIntegerInRange (s, 1, 31);
}

// daysInFebruary (INTEGER year)
// 
// Given integer argument year,
// returns number of days in February of that year.

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 );
}

// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day 
// form a valid date.
// 

function isDate (year, month, day)
{
  // catch invalid years (not 2- or 4-digit) and invalid months and days.
  if (! (isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;

  // Explicitly change type to integer to make code work in both
  // JavaScript 1.1 and JavaScript 1.2.
  var intYear = parseInt(year);
  var intMonth = parseInt(month);
  var intDay = parseInt(day);

  // catch invalid days, except for February
  if (intDay > daysInMonth[intMonth]) return false; 

  if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

  return true;
}

// isAddress (STRING sFieldValue [, BOOLEAN required==true])
//
// Returns true if string sField contains digits, letters and special chars only

function isAddress (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isAddress.arguments.length == 1) return defaultEmptyOK;
    else return (!isAddress.arguments[1]);

  // Search through string's characters one by one
  // until we find a non-address character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < sFieldValue.length; i++)
  {   
    // Check that current character is letter.
    var c = sFieldValue.charAt(i);

    if (validAddressChars.indexOf(c) == -1) return false;
  }

  // All characters are letters.
  return true;
}


// isAlphabetic (STRING sFieldValue [, BOOLEAN required==true])
// Returns true if string sField contains only letters 

function isAlphabetic (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isAlphabetic.arguments.length == 1) return defaultEmptyOK;
    else return (!isAlphabetic.arguments[1]);

  // Search through string's characters one by one
  // until we find a non-alphabetic character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < sFieldValue.length; i++)
  {   
    // Check that current character is letter.
    var c = sFieldValue.charAt(i);

    if (!isLetter (c))
      return false;
  }

  // All characters are letters.
  return true;
}


// isAlphanumeric (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue contains (A .. Z, a..z) and numbers only.

function isAlphanumeric (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isAlphanumeric.arguments.length == 1) return defaultEmptyOK;
    else return (!isAlphabetic.arguments[1]);
  
  // Search through string's characters one by one
  // until we find a non-alphanumeric character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < sFieldValue.length; i++)
  {   
    // Check that current character is number or letter.
    var c = sFieldValue.charAt(i);
  
    if (! (isLetterOrDigit (c) ) )
      return false;
  }
  
  // All characters are numbers or letters.
  return true;
}

// isPhoneNumber (STRING sFieldValue [, BOOLEAN required==true])
// 
// Returns true if string sFieldValue contains ( 0 .. 9, (, ), - ) only.
function isPhoneNumber (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
    else return (!isPhoneNumber.arguments[1]);
  
  // Search through string's characters one by one
  // until we find a non-phone character.
  // When we do, return false; if we don't, return true.
  for (var i = 0; i < sFieldValue.length; i++)
  {   
    // Check that current character is number or letter.
    var c = sFieldValue.charAt(i);
  
    if (validPhoneChars.indexOf(c) == -1) return false;
  }
  
  // All characters are valid phone chars.
  return true;
}

// isEmail (STRING sFieldValue [, BOOLEAN required==true])
// 
// 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
function isEmail (sFieldValue)
{
  if (isEmpty(sFieldValue))
    if (isEmail.arguments.length == 1) return defaultEmptyOK;
    else return (!isEmail.arguments[1]);
   
  // there must be >= 1 character before @, so we
  // start looking at character position 1 
  // (i.e. second character)
  var i = 1;
  var sLength = sFieldValue.length;

  // look for @
  while ((i < sLength) && (sFieldValue.charAt(i) != "@"))
    i++;

  if ((i >= sLength) || (sFieldValue.charAt(i) != "@")) return false;
  else i += 2;

  // look for .
  while ((i < sLength) && (sFieldValue.charAt(i) != "."))
    i++;

  // there must be at least one character after the .
  if ((i >= sLength - 1) || (sFieldValue.charAt(i) != ".")) return false;
  else return true;
}



/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */

// Display prompt string s in status bar.

function prompt (s)
{
  window.status = s;
}


// Display data entry prompt string s in status bar.

function promptEntry (s)
{
  window.status = pEntryPrompt + s;
}


// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, sMessage)
{
  theField.focus();
  alert(mPrefix + sMessage + mSuffix);
  return false;
}


// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, put focus in it, and return false.

function warnInvalid (theField, sMessage)
{
  theField.focus();
  theField.select();
  alert(sMessage);
  return false;
}


/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */

// checkAddress (TEXTFIELD theField, STRING s [, BOOLEAN required==true])
//
// Check that string theField.value is not all whitespace.

function checkAddress (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkAddress.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkAddress.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isAddress(theField.value))
    return warnInvalid(theField, iAddress);

  return true;
}


// checkCheckBoxes (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check if one of the check boxes is checked.

function checkCheckBoxes(theField, sMessage)
{
  for (var i = 0; i < theField.length; i++)
  {
    if (theField[i].checked) return true;
  }

  if ((checkCheckBoxes.arguments.length == 2) || ((checkCheckBoxes.arguments.length == 2) && (checkCheckBoxes.arguments[2] == true)))
    alert(sMessage + iCheckBoxSuffix);

  return false;
}


// checkDate (yearField, monthField, dayField, STRING sMessage [, BOOLEAN required==true, OKtoOmitDay==false])
//
// Check that yearField.value, monthField.value, and dayField.value 
// form a valid date.
//
// If they don't, sMessage (the name of the date, like "Birth Date")
// is displayed to tell the user which date field is invalid.
//
// If it is OK for the day field to be empty, set optional argument
// OKtoOmitDay to true.  It defaults to false.

function checkDate (yearField, monthField, dayField, sMessage)
{
  if (checkDate.arguments.length == 4) OKtoOmitDay = false;
  if ( (OKtoOmitDay == true) && isEmpty(dayField.value) ) return true;
  else if (!isDay(dayField.value)) 
         return warnInvalid (dayField, iDay);
  if (!isMonth(monthField.value)) return warnInvalid (monthField, iMonth);
  if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);

  if (isDate (yearField.value, monthField.value, dayField.value))
    return true;
  alert (iDatePrefix + sMessage + iDateSuffix);
  return false;
}


// checkDay (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check that string theField.value is a valid Day.

function checkDay (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkDay.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkDay.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isDay(theField.value, false)) 
    return warnInvalid (theField, iDay);
  else return true;
}


// checkEmail (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check that string theField.value is a valid Email.

function checkEmail (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkEmail.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkEmail.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isEmail(theField.value, false))
    return warnInvalid (theField, iEmail);
  else return true;
}


// checkMonth (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check that string theField.value is a valid Month.

function checkMonth (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkMonth.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkMonth.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isMonth(theField.value, false)) 
    return warnInvalid (theField, iMonth);
  else return true;
}


// checkPhoneNumber (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check that string theField.value is a valid Phone Number.

function checkPhoneNumber (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkPhoneNumber.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkPhoneNumber.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isPhoneNumber(theField.value, false))
    return warnInvalid (theField, iPhone);
  else return true;
}


// checkRadioButtons (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check if one of the radio button is selected.

function checkRadioButtons(theField, sMessage)
{
  for (var i = 0; i < theField.length; i++)
  {
    if (theField[i].checked) return true;
  }

  if ((checkRadioButtons.arguments.length == 2) || ((checkRadioButtons.arguments.length == 2) && (checkRadioButtons.arguments[2] == true)))
    alert(sMessage + iRadioSuffix);

  return false;
}


// checkString (TEXTFIELD theField, STRING s, INTEGER type [, BOOLEAN required==true])
//
// Check that string theField.value is not all whitespace.

function checkString (theField, sMessage, type)
{
  if (isWhitespace(theField.value))
    if (checkString.arguments.length == 3) return warnEmpty (theField, sMessage);
    else if (checkString.arguments[3] == false) return true;
         else return warnEmpty (theField, sMessage);

  switch (type)
  {
    case 0 : // Numeric Control
      if (!isInteger(theField.value))
        return warnInvalid(theField, iNumeric);
      break;
    case 1 : // Alphabetic Control
      if (!isAlphabetic(theField.value))
        return warnInvalid(theField, iAlphabetic);
      break;
    case 2 : // AlphaNumeric Control
      if (!isAlphanumeric(theField.value))
        return warnInvalid(theField, iAlphanumeric);
      break;
    default : // AlphaNumeric Control
      if (!isAlphanumeric(theField.value))
        return warnInvalid(theField, iAlphanumeric);
  }

  return true;
}


// checkYear (TEXTFIELD theField, STRING sMessage [, BOOLEAN required==true])
//
// Check that string theField.value is a valid Year.

function checkYear (theField, sMessage)
{
  if (isWhitespace(theField.value))
    if (checkYear.arguments.length == 2) return warnEmpty (theField, sMessage);
    else if (checkYear.arguments[2] == false) return true;
         else return warnEmpty (theField, sMessage);

  if (!isYear(theField.value, false)) 
    return warnInvalid (theField, iYear);
  else return true;
}


