/* validate.js

   form validation linked to lib/FormBuilder.pm

   Copyright 2007 Dragonstaff Limited. All rights reserved.
   
*/

// String.trim() - add trim() method to String object prototype
//   removes leading and trailing spaces from a string
String.prototype.trim = function() { return this.replace(/^[\s\u3000]+|[\s\u3000]+$/g, ''); }

// validfield_date_en_gb(e) - validate a date input field and rewrite to standard UK format
//   input: e - form field element
//   action: modifies e.value to standardised date, showing alert warning if invalid format
//   return: none
// depends on including the http://www.datejs.com date library date-en-GB.js to enhance the Date object
function validfield_date_en_gb(e)
{
  var s = e.value.trim();
  if (s == '') return; // blank is valid
  var d1 = Date.parse(s);
  if ( d1 == null ) // add on cases for ddmmyy and ddmmccyy
  {
    var d2 = s.match(/^(\d\d)(\d\d)(\d\d)$/); // try ddmmyy
    if ( d2 == null ) d2 = s.match(/^(\d\d)(\d\d)(\d\d\d\d)$/); // otherwise try ddmmccyy
    if ( d2 != null ) d1 = Date.parse( d2[1] + "/" + d2[2] + "/" + d2[3] ); // if found reformat and try to use as a date
  }
  if ( d1 == null )
  {
    alert('invalid date');
    window.setTimeout(function(){ e.focus(); e.select(); }, 50);
    return;
  }
  e.value = d1.toString('dd/MM/yyyy');
}
