var ff_ServerTime = (new Date()).getTime();

//********************************** FUNCTION FormatString **********************************
//* The function takes a passed in text input field and chacks if the data entered is valid
//* and formats it if it is.
//* parameters: FieldIn       The field to be validated
//*       FormatIn      A format string the field is to be formatted to
//*       Required      (true/false) True the field must have data, false it can be null
//*       MinNumChars     The minimum number of characters the field's string can be (not including format)
//*                 so SSN will have a MinNumChars = 9 even though the format string is 11.
//*                 0 or -1 means no limit.
//*       MaxNumChars     The maximum number of characters the field's string can be (not including format)
//*                 so SSN will have a MaxNumChars = 9 even though the format string is 11.
//*                 0 or -1 means no limit.
//*       AdditionalChars   These are a string of characters that can be added to the base format types
//*                 (numeric,alpha only, and alpha-numeric).  So asy you have a name field with a
//*                 FormatIn of "A", to allow -. etc pass in ".-'" into AdditionalChars.  In  other words
//*                 they are extra non-formatting character the user can input
//*       removeLeadingNulls : remove all 0-s from the beginning (added by Makar)
//*       leaveAloneZero : RGB: previous functionality: if removeLeadingNulls=true then stand-alone 0 also
//*                 will be removed. To keep alone 0 before use leaveAloneZero=true.
//*                 sample: '033'   FormatString(...,true)      '33'
//*                         '0'     FormatString(...,true)      ''
//*                         '0'     FormatString(...,true,true) '0'
//*                         '0.33'  FormatString(...,true)      '.33'
//*                         '0.33'  FormatString(...,true,true) '0.33'
//*
//* examples: for zip codes     onBlur="FormatString(this,"#",true,5,5,"");"
//*       for SSN       onBlur="FormatString(this,"###-##-####",true,9,9,"");"
//*       for phone number  onBlur="FormatString(this,"(###) ###-####",true,10,10,"");"
//*       for name      onBlur="FormatString(this,"A",true,2,30,".'-");"
//*       for dollar      onBlur="FormatString(this,"$#,##0.00",true,-1,-1,"");"
//********************************************************************************************
function FormatString(FieldIn,FormatIn,Required,MinNumChars,MaxNumChars,AdditionalChars,message,removeLeadingNulls,leaveAloneZero){
var RefString="";
var StrippedString="";
var NumDecPlaces=0;
var temp = "";
var DecPoint = 0;
var floatnumber = "";
var removeZero = 0;
var flength = 0;
var Number = "";
var CommaPlace = 0;
var FormattedString = "";
var IllegalEntry = false;
var NumLength = 0;
var StringIndex = 0;
var StringIn = FieldIn.value;
var tempString = "";
var mssge = "";
var rm_ldng_nulls = false;


  if(removeLeadingNulls != null){
    rm_ldng_nulls = removeLeadingNulls;
  }
  // seeing if data was entered
  if (StringIn == null || StringIn == "" ){
    if (Required == true){
      alert('This is a required field, you must enter a value.');
      FieldIn.focus();
      return("");
    }else{
      return(StringIn);
    }
  }
  if (IllegalEntry == false){

    FormatIn = trim(FormatIn);
    if (FormatIn == null || FormatIn == ""){
    // there is no format so don't bother formatting it
      StrippedString = StringIn;
      FormattedString = StringIn;
      type = 99;
    }else if (FormatIn.indexOf('#') != -1 || FormatIn.indexOf('0') != -1){
    // assuming it is a number format
      RefString="1234567890." + AdditionalChars;
      // stripping out all non numbers
      for (Count=0; Count < StringIn.length; Count++){
        temp = StringIn.substring (Count, Count+1);
        if (RefString.indexOf(temp) != -1){
          StrippedString=StrippedString+temp;
        }
      }

      //removing trailing dot.
      if(StrippedString.lastIndexOf('.')==StrippedString.length-1){
        StrippedString = StrippedString.substring(0,StrippedString.length-1);
      }

      if(rm_ldng_nulls){
        while(true){
          if(StrippedString.length == 0){
            break;
          }
          if(leaveAloneZero && StrippedString.length == 1){
            break;
          }
          if(StrippedString.substring(0,1)=="0"){
            if(leaveAloneZero){
              if("1234567890".indexOf(StrippedString.substring(1,2))==-1){
                break;
              }
            }
            StrippedString = StrippedString.substring(1,StrippedString.length);
          }
          else{
            break;
          }
        }
      }
      type = 0;
    }else if (FormatIn.indexOf('A') != -1 || FormatIn.indexOf('U') != -1){

    // assuming it is a alpha only format format
      RefString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"  + AdditionalChars;
      for (Count=0; Count < StringIn.length; Count++){
      // stripping out all non letters
        temp = StringIn.substring (Count, Count+1);
        if (RefString.indexOf(temp) != -1){
          StrippedString=StrippedString+temp;
        }
      }
      if (FormatIn.indexOf('U') != -1){
        StrippedString = StrippedString.toUpperCase();
      }
      type = 1;
    }
    else if (FormatIn.indexOf('?') != -1){
    // assuming it is an alph-numeric entry
      RefString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"  + AdditionalChars;
      for (Count=0; Count < StringIn.length; Count++)
      {
      // stripping out all non alpha-numeric characters
        temp = StringIn.substring (Count, Count+1);
        if (RefString.indexOf(temp) != -1){
          StrippedString=StrippedString+temp;
        }
      }
      type = 2;
    }else{
    // Either there is no format or an unreconized format so treating it as none.
      StrippedString = StringIn;
      FormattedString = StringIn;
      type = 99;
    }

    StringIn = StrippedString;
    NumLength = StringIn.length;
    var FormatLen = FormatIn.length;
    if ((NumLength < MinNumChars)  || (MaxNumChars < NumLength && MaxNumChars != -1)){
    // no enough characters entered.
      IllegalEntry = true;
    }else if (type == 0){

      //alert("FormatIn: " + FormatIn);
      var DecIndex = FormatIn.indexOf(".");
      if (DecIndex != -1){
      //Assuming it is a decimal format thus determining the number of decimal places
        NumDecPlaces = FormatLen - DecIndex - 1;
        temp = "" + Math.round(parseFloat(StringIn) * Math.pow(10,NumDecPlaces));
        DecPoint = temp.length - NumDecPlaces;
        floatnumber = temp.substring(0,DecPoint) + "." + temp.substring(DecPoint,temp.length);
        removeZero = 0;
        flength = floatnumber.length;
        //finding out if zeros on the end are needed
        for (Count=1; Count <= NumDecPlaces; Count++){
          if (floatnumber.substring(flength - Count,flength) == "0" && FormatIn.substring(FormatLen - Count,FormatLen) != "0"){
            removeZero++
          }
        }
        if (removeZero == NumDecPlaces){
          Number = floatnumber.substring(0,flength - removeZero -1)
        }else{
          Number = floatnumber.substring(0,flength - removeZero)
        }
        //determining if a zero needs to be added before the decimal point so .3 will look like 0.3
        if (Number.substring(0,1) == "." && FormatIn.substring(DecIndex-1,DecIndex) == "0"){
          Number = "0" + Number;
        }
      }else{
        if (StringIn.indexOf(".") != -1){
        // the number has a decimal point in it and the formatting doesn't require one
          //temp = "" + Math.round(parseFloat(StringIn));
          //Number = temp;
    
          tempString = StringIn;

          tempString= StringIn.substring(0,StringIn.indexOf("."))+StringIn.substring(StringIn.indexOf(".")+1, StringIn.length-1);
          if(tempString.indexOf(".") != -1){
            IllegalEntry = true;
            mssge = "The number you entered is invalid. Please check it."
          }  
          Number = StringIn;
        }else{
          Number = StringIn;
        }
        if(Number.indexOf(".") == -1)
          DecPoint = Number.length;
        else
          DecPoint = Number.indexOf(".");
      }
      if (StringIn.indexOf(".") == 0){
        StringIn = "0"+StringIn;
      }  

      if (FormatIn.indexOf(",") != -1){
      //determining if commas are needed
        CommaPlace = DecPoint - 3;
        while (CommaPlace > 0)
        {
          Number = Number.substring(0,CommaPlace) + "," + Number.substring(CommaPlace,Number.length);
          CommaPlace = CommaPlace - 3;
        }
        //checking if there is a prefix; example: '$'
        temp = FormatIn.substring(0,1);
        if (temp != "0" && temp != "#")
        {
          FormattedString = temp + Number;
        } else {
          FormattedString = Number;
        }
        // alert(FormattedString);
      }
      else if (FormatLen > 1)
      {
      // formatting non value numbers like SSN instead of number like a dollar amount
        for (i = 0; i < FormatLen; i++)
        {
          temp = FormatIn.substring(i,i+1)
          if (temp != "0" && temp != "#")
          {
            FormattedString = FormattedString + temp;
          }
          else if (StringIndex < StringIn.length)
          {
            FormattedString = FormattedString + StringIn.substring(StringIndex,StringIndex+1)
            StringIndex++;
          }
          else if (temp == "0")
          {
            FormattedString = FormattedString + "0"
          }
          else
          {
            IllegalEntry = true;
          }
        }
      }
      else
      {
        FormattedString = StringIn;
      }
    }
    else if (type != 99 && FormatLen > 1)
    {
    //formatting non digit entries
      for (i = 0; i < FormatLen; i++)
      {
        temp = FormatIn.substring(i,i+1);
        if (temp != "A" && temp != "?")
        {
          FormattedString = FormattedString + temp;
        }
        else if (StringIndex < StringIn.length)
        {
          FormattedString = FormattedString + StringIn.substring(StringIndex,StringIndex+1)
          StringIndex++;
        }
        else
        {
          IllegalEntry = true;
        }
      }

    }
    else
    {
      FormattedString = StringIn;
    }
  }

  if (IllegalEntry == true)
  {
    FormattedString = "";
    if(mssge.indexOf("The number you entered is invalid. Please check it.") == -1)
      mssge = "The data you entered in "+ message + " is invalid.\n It must be at least " + MinNumChars +" but no more than " + MaxNumChars + " characters.";
    alert(mssge);
    FieldIn.focus();
  }

  FieldIn.value = FormattedString;
  return(FormattedString);
}

function remove_leading_zeroes(str){
  while(true){
    if(str.charAt(0)!="0"){
      return str;
    }
    str = str.substring(1,str.length);
  }
}

function validDate(field){
var dateField; dateField = field.value;
var today = new Date();
var f; var month = ""; var merror = 0; var date = ""; var derror = 0; var year = ""; var yerror = 0;
// do not process field if nothing is entered, but set AGE to 0 to signify nothing entered
if (dateField.length != 0){
  // parse out date field to separate month, date, and year
  // tokens are separated by any non-numeric characters, will be reformatted later
  for ( j=0; j<dateField.length; j++ ){
    if( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") ){
      i = j;
      while ( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") )
        j++;
      if ( month.length == 0 )
        month = dateField.substring(i,j);
      else{
        if ( date.length == 0 )
          date = dateField.substring(i,j);
        else{
          year = dateField.substring(i,dateField.length + 1);
          break;
          }
        }
      }
    }
  
  //removing leading zeroes
    month = remove_leading_zeroes(month);
    date = remove_leading_zeroes(date);
    year = remove_leading_zeroes(year);

  // reformat fields if necessary
  if ( month.length == 1 )
    month = "0" + month;
  if ( date.length == 1 )
    date = "0" + date;
  if ( year.length == 1 )
    year = "0" + year;
  if ( year.length == 2 )
    year = "20" + year;
  // check valid dates for each month
  f = parseFloat(month);
  // only 12 months in a year
  if ( (f > 12) || (f < 1) || ( month.length == 0 ) )
    merror = 1;
  if ( date.length == 0 )
    derror = 1;
  // april, june, september, and november each have 30 days
  else{
    if ( ((f == 4) || (f == 6) || (f == 9) || (f == 11)) && ( parseFloat(date) > 30 || parseFloat(date) < 1 ))
      derror = 1;
    // january, march, may, july, august, october and december have 31 days
    if ( ((f == 1) || (f == 3) || (f == 5) || (f == 7) || (f == 8) || (f == 10) || (f == 12) ) && ( parseFloat(date) > 31 || parseFloat(date) < 1 ))
      derror = 1;
    // february has 28 days, leap years ( those divisible by 4 or 400 and not by 100) have 29 days
    if ( ( f == 2 ) && ( parseFloat(date) >
        ( (parseFloat(year)%4 == 0) && (((parseFloat(year)% 100)!=0) || ((parseFloat(year)% 400)==0)) ? 29 : 28 ) || parseFloat(date) < 1 ))
      derror = 1;
    }
  // check valid years, two digit years are assumed to be in 1900's ( should be valid for
  // next 20 years!!). javascript date years are 70 onward ( with 100 being year 2000 )
  if ( (year.length != 4) || !isNumberString(year) )
    yerror = 1;
  if ( (merror == 0) && (derror == 0) && (yerror == 0) ){
    dateField = month + "/" + date + "/" + year;
    field.value = dateField;
    return(true);
    }
  // else display error message and set focus to date field
  else{
    alert("\nDate Error!!\n\nInvalid Date Entered.\nEnter Only Valid Dates in MM/DD/YYYY or MM/DD/YY format.");
    field.focus();
    return(false);
    }
  }
}


function isNumberString (InString){
  var regexp = /^[\d.]+$/g;
  if (InString.search(regexp) < 0) {
    return (false);
  }
  return (true);
}

function AddDaysToDate(NumOfDays, DateStart, DateResult) {
  if (NumOfDays.value == "") return (false);
    var dateField; dateField = DateStart;
    //alert(dateField);
    var today = new Date();
    var f; var month = ""; var merror = 0; var date = ""; var derror = 0; var year = ""; var yerror = 0;

  // parse out date field to separate month, date, and year
  // tokens are separated by any non-numeric characters, will be reformatted later
  for ( j=0; j<dateField.length; j++ ){
    if( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") ){
      i = j;
      while ( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") )
        j++;
      if ( month.length == 0 )
        month = dateField.substring(i,j);
      else{
        if ( date.length == 0 )
          date = dateField.substring(i,j);
        else{
          year = dateField.substring(i,dateField.length + 1);
          break;
          }
        }
      }
    }
  var intDay=0;
  intDay=parseFloat(date);
  //alert("Date = " + date + ", intDay = " + intDay);
  var intYear=0;
  intYear=parseFloat(year);
  var intMonth=0;
  intMonth=parseFloat(month);
  //alert("Month = " + month + ", intMonth = " + intMonth);
  var DaysToAdd=parseFloat(NumOfDays.value);
  intDay=intDay+DaysToAdd;
  //alert(intMonth + "/" + intDay + "/" + intYear);

  // april, june, september, and november each have 30 days
  if ( (intMonth == 4) || (intMonth == 6) || (intMonth == 9) || (intMonth == 11) )
  {
    if (intDay > 30) {intDay = intDay-30; intMonth = intMonth + 1;}
  }
  // january, march, may, july, august, october and december have 31 days
  if ( (intMonth == 1) || (intMonth == 3) || (intMonth == 5) || (intMonth == 7) || (intMonth == 8) || (intMonth == 10) || (intMonth == 12) )
  {
    if (intDay > 31) {intDay = intDay-31; intMonth = intMonth + 1;}
  }
  // february has 28 days, leap years ( those divisible by 4 or 400 and not by 100) have 29 days
  if ( intMonth == 2 )
  {
      daysInFeb = ( (intYear%4 == 0) && ( ( intYear%100!=0 ) || ( intYear%400 == 0 ) ) ) ? 29 : 28;
    if (intDay > daysInFeb) {intDay = intDay-daysInFeb; intMonth = intMonth + 1;}
  }

  // only 12 months in a year
  if (intMonth > 12)
  {
    intMonth = intMonth-12; intYear = intYear + 1;
  }

  if (intMonth < 10)
      DateResult.value = "0";

  DateResult.value = DateResult.value + intMonth + "/";

  if (intDay < 10)
      DateResult.value = DateResult.value + "0";

    DateResult.value = DateResult.value + intDay + "/" + intYear;

  return(true);
}

function SubtructDaysToDate(NumOfDays, DateStart, DateResult) {
  if (NumOfDays.value == "") return (false);
    var dateField; dateField = DateStart;
    //alert(dateField);
    var today = new Date();
    var f; var month = ""; var merror = 0; var date = ""; var derror = 0; var year = ""; var yerror = 0;

  // parse out date field to separate month, date, and year
  // tokens are separated by any non-numeric characters, will be reformatted later
  for ( j=0; j<dateField.length; j++ ){
    if( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") ){
      i = j;
      while ( (dateField.substring(j,j+1) >= "0") && (dateField.substring(j,j+1) <= "9") )
        j++;
      if ( month.length == 0 )
        month = dateField.substring(i,j);
      else{
        if ( date.length == 0 )
          date = dateField.substring(i,j);
        else{
          year = dateField.substring(i,dateField.length + 1);
          break;
          }
        }
      }
    }
  var intDay=parseFloat(date);
  var intYear=parseFloat(year);
  var intMonth=parseFloat(month);
  //alert("Month = " + month + "intMonth = " + intMonth);
  var DaysToAdd=parseFloat(NumOfDays.value);
  intDay=intDay-DaysToAdd;
  //alert(intDay);

  if ( intDay < 1 )
  {
    intMonth = intMonth - 1;

    // april, june, september, and november each have 30 days
    if ( (intMonth == 4) || (intMonth == 6) || (intMonth == 9) || (intMonth == 11) )
    {
      intDay = 30 + intDay;
    }
    // january, march, may, july, august, october and december have 31 days
    if ( (intMonth == 1) || (intMonth == 3) || (intMonth == 5) || (intMonth == 7) || (intMonth == 8) || (intMonth == 10) || (intMonth == 12) )
    {
      intDay = 31 + intDay;
    }
    // february has 28 days, leap years ( those divisible by 4 or 400 and not by 100) have 29 days
    if ( intMonth == 2 )
    {
        daysInFeb = ( (intYear%4 == 0) && ( ( intYear%100!=0 ) || ( intYear%400 == 0 ) ) ) ? 29 : 28;
      intDay = daysInFeb - intDays;
    }
  }
  // only 12 months in a year
  if (intMonth < 1)
  {
    intMonth = 12 + intMonth; intYear = intYear - 1;
  }

  if (intMonth < 10)
      DateResult.value = "0";

  DateResult.value = DateResult.value + intMonth + "/";

  if (intDay < 10)
      DateResult.value = DateResult.value + "0";

    DateResult.value = DateResult.value + intDay + "/" + intYear;

  return(true);
}


function validNumber(field, str) {
  if (!isNumberString(field.value) && !field.value == "") {alert(str); field.value=""; return;}
  else return;
}


//<!----- DAYS and DATE Operations ---->

// Calculate difference between inpDateEnd.value and inpDateStart.value. Output result to
// inpNumberDays.value.
function DaysInPeriod(inpDateStart, inpDateEnd, inpNumberDays)
{
    inpNumberDays.value = "";
    if (inpDateStart.value == "" || inpDateEnd.value == "") return ;
    DateStart = parseDate(inpDateStart);
    DateEnd = parseDate(inpDateEnd);
    var days = 'error' ;
    if (DateStart != null && DateEnd != null)
    {
        //alert ("DateStart = " + DateStart + " and DateEnd = " + DateEnd);
        startTime = DateStart.getTime();
        endTime = DateEnd.getTime();
        diffTime = endTime - startTime;
        if (diffTime < 0) {
            alert("ERROR: Start Date later end Date, check your Dates input: " + Math.round(diffTime / 24 / 60 / 60 / 1000));
            return "";
        }
        days = Math.round(diffTime / 24 / 60 / 60 / 1000);

    }
     inpNumberDays.value = days.toString();
     //alert("inpNumberDays = " + inpNumberDays.value + "\/ days = " + days);
     return days;
}

//
// Date checking.
//

function checkDateIsNotPast( date ) {
  if(date == null)return false;
  newdate = new Date(date.getTime());
  newdate.setHours(23);
  newdate.setMinutes(59);
  newdate.setSeconds(59);
  var isNotPast = ( newdate.getTime() - parseInt(ff_ServerTime,10) >= 0 );
  if( ! isNotPast ) {
    alert("Please, check the date. It's earlier than today.");
  }
  return isNotPast;
}

//
// Time checking.
//

function parseTime( field ) {
  var regexp_empty = /^\s*$/;
  if( regexp_empty.test( field.value ) ) return -1;
  var regexp_time = /^\s*(\d+)\s*(:\s*(\d+)\s*)?\s*(([aApP])[mM]?)?\s*$/;
  var error_msg = "Enter valid time, please (for example: '2:00PM')";
  if( ! regexp_time.test( field.value.toUpperCase() ) ) { alert( error_msg ); return -1; }
  var iHours = parseInt( RegExp.$1, 10 );
  var iMinutes = ( RegExp.$3 == "" ? 0 : parseInt( RegExp.$3, 10 ) );
  var sAmPm = RegExp.$5; // "P"/"A"/"";
  if( sAmPm == "" ) {
    if( iHours == 0 ) { iHours = 12; sAmPm = "A"; }
    else if( iHours > 12 ) { iHours -= 12; sAmPm = "P"; }
    else if( 7 <= iHours && iHours <= 11 ) { sAmPm = "A"; }
    else { sAmPm = "P"; }
  }
  if( iHours < 1 || iHours > 12 ) { alert( error_msg ); return -1; }
  var iHours24 = ( iHours == 12 ? 0: iHours );
  if( sAmPm == "P" ) iHours24 += 12;
  return iMinutes + 60 * iHours24;
}

function formatTime( mins ) {
  if( mins < 0 ) return "";
  var iHours24 = parseInt( mins / 60, 10 ) % 24;
  var iMinutes = mins % 60;
  var iHours = iHours24 % 12;
  if( iHours == 0 ) iHours = 12;
  sAmPm = ( iHours24 < 12 ? "A" : "P" );
  return "" + iHours + ":" + ( iMinutes < 10 ? "0" : "" ) + iMinutes + " " + sAmPm + "M";
}

function checkTimeEntry( field, isAlert, isRequired ) {
  var mins = parseTime( field );
  field.value = ( mins < 0 ? "" : formatTime( mins ) );
  return mins >= 0;
}

//
// Currency checking
//

function parseCurrency( field ) {
  var regexp_skip = /[,\044\s]/g;
  var value = parseInt( field.value.replace( regexp_skip, "" ) );
  if( isNaN( value ) ) value = 0.00;
  return value;
}

function formatCurrency( value ) {
 // --- cents ---
 // value = parseInt( value * 100, 10 );
  //var digits = value % 100;
  //var result = "." + ( digits < 10 ? "0" : "" ) + digits;
  //value = parseInt( value / 100, 10 );
  value = parseInt( value, 10);
  var result = "";
  while( true ) { // forever
    digits = value % 1000;
    value = parseInt( value / 1000, 10 );
    if( value > 0 ) {
      result = "," + ( digits < 10 ? "00" : digits < 100 ? "0" : "" ) + digits + result;
    } else {
      result = "" + digits + result;
      break;
    }
  }
  return "$" + result;
}

function checkCurrency( field ) {
  var value = parseCurrency( field );
  field.value = ( value <= 0 ? "": formatCurrency( value ) );
  return value > 0;
}

//----------------

//
// Check empty entry
//

function checkEmptyField( field ) {
if((field.value!="") && (field.type=="text")){ 
  stripSpaces( field );
}
  if( field.value == "") {
    return true;
  }
  return false;
}

var parse_error_msg;

//
// EMail checking
//

function parseEMailField( field ) {
//  var regexp_email = /^[\w-_.]+\@([\w-_]+\.)+\w{2,4}$/g;
//  if( field.value.search( regexp_email ) < 0 ) return null;
    var emailReg = "^\\w[\\w-_+\.]*\@([\\w-_]+\\.)+[\\w-_]+\\w$";
    var regex = new RegExp(emailReg);
    if( !regex.test(field.value) ) return null;
  return field.value;
}

function checkEMailField( field, isAlert, isRequired ) {
  parse_error_msg = "Please, enter valid e-mail address (for example: 'john@email.com')";
  if( checkEmptyField( field ) ) {
    if( isRequired ) {
      if( isAlert ) { alert( parse_error_msg ); field.focus(); }
      return false;
    }
    return true;
  }
  stripSpaces( field );
  var email = parseEMailField( field );
  if( email == null ) {
    if( isAlert ) { alert( parse_error_msg ); field.focus(); }
    return false;
  }
  field.value = email;
  return true;
}

function parseEMailNameField( field ) {
//  var regexp_email = /^[\w-_.]+\@([\w-_]+\.)+\w{2,4}$/g;
//  if( field.value.search( regexp_email ) < 0 ) return null;
    var emailReg = "^\\w[\\w-_+\.]*$";
    var regex = new RegExp(emailReg);
    if( !regex.test(field.value) ) return null;
  return field.value;
}

function checkEMailNameField( field, isAlert, isRequired ) {
  parse_error_msg = "Please, enter valid e-mail name (for example: 'john.black')";
  if( checkEmptyField( field ) ) {
    if( isRequired ) {
      if( isAlert ) { alert( parse_error_msg ); field.focus(); }
      return false;
    }
    return true;
  }
  stripSpaces( field );
  var email = parseEMailNameField( field );
  if( email == null ) {
    if( isAlert ) { alert( parse_error_msg ); field.focus(); }
    return false;
  }
  field.value = email;
  return true;
}


function trim(val){
  if (val == null) {
    return '';
  }
  while(true){
    if(val.charAt(0) == " "){
      val=val.substring(1,val.length);
    }
    else{
      break;
    }
  }
  while(true){
    if(val.charAt(val.length-1) == " "){
      val=val.substring(0,val.length-1);
    }
    else{
      break;
    }
  }
  return val;
}


/*function trim(str) {

  var source_str = str;
  var result_str = source_str;
  var strip_class = "   ";

  for(i=0;i < source_str.length;i++){
    var cur_char = source_str.substring(i,i+1);
    if (strip_class.indexOf(cur_char) != -1 ) {
      result_str = source_str.substring(i+1)
    } else {
      break;
    }
  }

  for(i=source_str.length;i > 0;i--){
    var cur_char = result_str.substring(i,i-1);
    if (strip_class.indexOf(cur_char) != -1) {
      result_str = result_str.substring(0,i-1)
    } else {
      break;
    }
  }

  return result_str;
}*/

function stripSpaces(field){
  field.value = trim(field.value);
}

//
// Date checking
//

/*
 * get input field, which has contain ....MM...DD...YYYY(YY or even Y). I mean any simbols between
 * Month number, Day, Year. Last one can be four-digits, two-digits: 20YY and one-digit: 200Y.
 */

function checkDateEntry( field ) {
  parse_error_msg = "Please, enter valid date (for example: '12/31/2001' or '12/31/01')";
  if( checkEmptyField( field ) ) {
    alert( parse_error_msg ); 
    field.focus();
    return false;
  }
  var date = parseDateField( field );
  if( date == null ) {
    alert( parse_error_msg ); 
    field.value = "";
    field.focus(); 
    return null;
  }
  field.value = formatDateField( date );
  return date;
}

function parseDateField( field ) {
  var regexp_date = /^\s*(\d+)\W+(\d+)\W+(\d+)\s*$/;
  if( ! regexp_date.test( field.value ) ) return null;
  var iMonth = parseInt( RegExp.$1, 10 );
  var iDay = parseInt( RegExp.$2, 10 );
  var iYear = parseInt( RegExp.$3, 10 );
  if( iYear < 1000 ) iYear += 2000;
  var date = new Date( iYear, iMonth - 1, iDay, 0, 0, 0, 0 );
  if( date.getMonth() != iMonth - 1 || date.getDate() != iDay || date.getFullYear() != iYear ) return null;
  return date;
}

function formatDateField( date ) {
  var text =
    "" + ( date.getMonth() + 1 < 10 ? "0" : "" ) + ( date.getMonth() + 1 )
    + "/" + ( date.getDate() < 10 ? "0" : "" ) + date.getDate()
    + "/" + date.getFullYear();
  return text;
}

function checkDateField( field, isAlert, isRequired ) {
  parse_error_msg = "Please, enter valid date (for example: '12/31/2001' or '12/31/01')";
  if( checkEmptyField( field ) ) {
    if( isRequired ) {
      if( isAlert ) { alert( parse_error_msg ); field.focus(); }
      return false;
    }
    return true;
  }
  var date = parseDateField( field );
  if( date == null ) {
    if( isAlert ) { alert( parse_error_msg ); field.focus(); }
    return false;
  }
  field.value = formatDateField( date );
  return true;
}

//
// Phone checking
//

function checkPhone( field ) {
  return checkPhoneField( field, true, true );
}

function parsePhoneField( field ) {
  var regexp_skip = /[\W]/g;
  var value = field.value.replace( regexp_skip, "" );
  parse_error_code = 0;
  if( value.length == 0 ) return null;
  if( value.length < 10 ) return null;
  parse_error_msg = "Please, check phone number - it is too long!";
  if( value.length > 18 ) return null;
  var phone =
    "(" + value.substr( 0, 3 ) + ") " + value.substr( 3, 3 ) + "-" + value.substr( 6, 4 )
    + ( value.length > 10 ? " #" + value.substr( 10 ) : "" );
  return phone;
}

function checkPhoneField( field, isAlert, isRequired ) {
  parse_error_msg = "Please, provide phone number include area code (for example: '(888) 123 4567')";
  if( checkEmptyField( field ) ) {
    if( isRequired ) {
      if( isAlert ) { alert( parse_error_msg ); field.focus(); }
      return false;
    }
    return true;
  }
  var phone = parsePhoneField( field );
  if( phone == null ) {
    if( isAlert ) { alert( parse_error_msg ); field.focus(); }
    return false;
  }
  field.value = phone;
  return true;
}

function isCommaSeparatedEmails(field) {
  var regexp = /^\s*[\.\w-_]+\@([\w-_]+\.)+\w{2,4}\s*(,\s*[\.\w-_]+\@([\w-_]+\.)+\w{2,4}\s*)*$/g;
  if(!regexp.test(field.value)) {
    alert('Please provide correct email addresses!');
    field.focus();
    return false;
  }
  return true;
}
//------------

function toHex( n, size ) {
  var hex_digits = "0123456789ABCDEF";
  var s = "";
  while( s.length < size ) {
    s = hex_digits.charAt( n % 16 ) + s;
    n = n / 16;
  }
  return s;
}

function checkValueSize(fld, low, high, isAlert, isFocus){
  if ( fld.value.length < low ){
    if (isAlert && (isAlert != "")) alert('Minimum filed size is ' + low);
    if (isFocus) fld.focus();
    return false;
  }
  
  if ( fld.value.length > high ){
    if (isAlert && (isAlert != "")) alert('Maximum filed size is ' + high);
    if (isFocus) fld.focus();
    return false;
  }
  return true;
}

/*function FormatPhone(fld){
  var val = trim(fld.value);
  for(var i=0; i<val.length; i++){
    if(val.charAt(i)=="(" || 
       val.charAt(i)=="(" ||

    )
  }
  var result = "";
  for (var i=0; i<val.length; i++){
    if(i==0){
      result += "(";
    }
    if(i==3){
      result += ") ";
    }
    if(i==6){
      result += "-";
    }
    if(i==10){
      result += " ext. ";
    }
    result +=val.charAt(i);
  }
  fld.value = result;
}
*/


  function checkURL(target){
    if (target.value.length > 0){
      if (target.value.indexOf("http://")!=0 && target.value.indexOf("https://")!=0){
        target.value = "http://" + target.value;
      }
    }
  }



  function CheckMaxPrice(fld, lclass, ls){

    //check for empty value first.
    if(fld.value==""){
      return true;
    }

    //test ls and lclass combibations.
    if(ls=="REIL"){
      if(lclass=="RENT" || lclass=="CRENT"){
        return true;
      }
    }else if(ls=="SOCAL"){
      if(lclass=="RLS"){
        return true;
      }
    }else if(ls=="MAXEBRDI"){
      if(lclass=="LEASE"){
        return true;
      }
    }else if(ls=="ACTRIS"){
      if(lclass=="LSE"){
        return true;
      }
    }else if(ls=="MRIS"){
      if(lclass=="RLS"){
        return true;
      }
    }else if(ls=="MLSNI"){
      if(lclass=="RNT"){
        return true;
      } 
    }

    //test max price value.
    if(fld.value < 1000){
      if(confirm("You entered price for listings less then $1000.\n Select OK to continue or Cancel to revisit search criteria.")){
        return true;
      }else{
        fld.focus();
        // clear flag.
        return false;
      }

    }
  }
