// Declaring valid date character, minimum year and maximum year
// date format for validation is dd-mm-yyyy
var dateSeparator = "-";
var minYear = 1900;
var maxYear = 2100;

function objectById(theId) {
  return document.getElementById(theId);
}

function valueById(theId) {
  return document.getElementById(theId).value;
}

function trimString(s) {
  return s.replace(/^\s*/, "").replace(/\s*$/, "");
}

function trimFieldById(theId) {
  var o = document.getElementById(theId);
  o.value = trimString(o.value);
}

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

function isValidNumber(val)
{
  if (val==null)
    return false;

  if (val.length==0)
    return false;

  var decimalFound = false;

  for (var i = 0; i < val.length; i++) {
    var ch = val.charAt(i);

   if (i == 0 && ch == "-")
     continue;

   if (ch == "." && !decimalFound)
     decimalFound = true;
     continue;
   }

   if (ch < "0" || ch > "9")
     return false;

   return true;
}

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++){
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) returnString += c;
  }
  return returnString;
}

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 );
}

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

function isValidDate(dtStr, fieldName) {
  var daysInMonth = DaysArray(12);
  var pos1=dtStr.indexOf(dateSeparator);
  var pos2=dtStr.indexOf(dateSeparator,pos1+1);
  var strDay=dtStr.substring(0,pos1);
  var strMonth=dtStr.substring(pos1+1,pos2);
  var strYear=dtStr.substring(pos2+1);
  strYr=strYear;

  var strDay2 = strDay;
  var strMonth2 = strMonth;

  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 for \"" + fieldName + "\" should be: dd-mm-yyyy");
    return false;
  }

  if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
    alert("Please enter a valid day for \"" + fieldName + "\"");
    return false;
  }

  if (strDay2.length != 2){
    alert("Please enter 2 digits day for \"" + fieldName + "\"");
    return false;
  }

  if (strMonth.length<1 || month<1 || month>12) {
    alert("Please enter a valid month for \"" + fieldName + "\"");
    return false;
  }

  if (strMonth2.length!=2) {
    alert("Please enter 2 digits month for \"" + fieldName + "\"");
    return false;
  }

  if (strYear.length != 4 || year==0 || year<minYear || year>maxYear) {
    alert("Please enter a valid 4 digit year between " + minYear + " and " + maxYear + " for \"" + fieldName + "\"");
    return false;
  }

  if (dtStr.indexOf(dateSeparator,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dateSeparator))==false){
    alert("Please enter a valid date for \"" + fieldName + "\"");
    return false;
  }

  return true;
}

function allValidEmailChars(email)
{
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function isValidEmailString(email)
{
  if (email.length==0)
    return false;
  if (!allValidEmailChars(email)) // check to make sure all characters are valid
    return false;
  if (email.indexOf("@") < 1) //  must contain @, and it must not be the first character
    return false;
  else if (email.lastIndexOf(".") <= email.indexOf("@"))  // last dot must be after the @
    return false;
  else if (email.indexOf("@") == email.length) // @ must not be the last character
    return false;
  else if (email.indexOf("..") >=0) // two periods in a row is not valid
    return false;
  else if (email.indexOf(".") == email.length)  // . must not be the last character
    return false;
  return true;
}

function isValidUrl(s)
{
  var p = s.indexOf("://");
  if (p<0) return false;
  var s1 = s.substring(0,p);
  if ((s1 != 'http') && (s1 != 'https'))
    return false;
//var regexp = /^http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
  var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  return regexp.test(s);
}

// these are useful functions for common form validation

function fieldIsEmpty(theId, fieldName) {
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  trimFieldById(theId);
  if (valueById(theId) == '') {
    objectById(theId).focus();
    var t = objectById(theId).type;
    if (t == 'select-one')
      alert('Silahkan pilih \"' + fieldName + "\"");
    else
      alert('Silahkan isi \"' + fieldName + "\"");
    return true;
  }
  else
    return false;
}

function fieldIntegerIsValid(theId, fieldName)
{
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  var o = objectById(theId);
  var s = valueById(theId);
  if (!isInteger(s)) {
    o.focus();
    alert("Silahkan \"" + fieldName + "\" dengan angka.");
    return false;
  }
  else
    return true;
}

function fieldNumberIsValid(theId, fieldName)
{
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  var o = objectById(theId);
  var s = valueById(theId);
  if (!isValidNumber(s)) {
    o.focus();
    alert("Silahkan isi \"" + fieldName + "\" dengan angka");
    return false;
  }
  else
    return true;
}

function fieldDateIsValid(theId, fieldName) {
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  var d = objectById(theId);
  var v = valueById(theId);
  var r = isValidDate(v, fieldName);
  if (!r)
    d.focus();
  return r;
}

function fieldEmailIsValid(theId, fieldName) {
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  if (!isValidEmailString(valueById(theId))) {
    objectById(theId).focus();
    alert("Email format untuk \"" + fieldName + "\" tidak valid.");
    return false;
  }
  else
    return true;
}

function fieldUrlIsValid(theId, fieldName) {
  fieldName = typeof(fieldName) != 'undefined' ? fieldName : theId;
  if (!isValidUrl(valueById(theId))) {
    objectById(theId).focus();
    alert("Url format for \"" + fieldName + "\" is not valid");
    return false;
  }
  else
    return true;
}

function fieldCheckMinLength(theId, fieldName, minimum)
{
  if (objectById(theId).disabled)
    return true;

  if (valueById(theId).length < minimum) {
    alert("Panjang minimum \"" + fieldName + "\" adalah " + minimum + " huruf.");
    objectById(theId).focus();
    return false;
  }
  else
    return true;
}

function fieldCheckMaxLength(theId, fieldName, maximum)
{
  if (objectById(theId).disabled)
    return true;

  if (valueById(theId).length > maximum) {
    alert("Panjang maksimum \"" + fieldName + "\" adalah " + maximum + " huruf.");
    objectById(theId).focus();
    return false;
  }
  else
    return true;
}

function fieldCheckRange(theId, fieldName, minimum, maximum)
{
  if (document.getElementById(theId).disabled)
    return true;

  var s = document.getElementById(theId).value;

  if (s.length < minimum || s.length > maximum) {
    alert("\"" + fieldName + "\" length must be between " + minimum + " and " + maximum + " characters.");
    document.getElementById(theId).focus();
    return false;
  }
  else
    return true;
}

