NN = (document.layers) ? 1 : 0; 
IE = (document.all) ? 1 : 0;
//******************************************************************************
var display="",
    display_pos=0;
//******************************************************************************
function ValidateForm(which)
{
 if (checkrequired(which)) 
    {
     SubmitForm1(which);
     return;
    } 
   
 return;
}

//******************************************************************************
function ValidatePrjForm(which)
{
 if (checkrequired(which) && checkPrjDates(which) ) 
     SubmitForm1(which);
 return;
}

//******************************************************************************
function checkrequired(which) 
{
 var error=0, field_title, tempobj, field_name="";
 if (document.images) 
    {
     for (i=0;i<which.length;i++) 
         {
          tempobj=which.elements[i];
          field_name=GetFieldName(tempobj.name);
          error=CheckRequiredField(which,tempobj,field_name);
          if (error>0) break;
          error=CheckForbiddenSymbols(which,tempobj);
          if (error>0) break;
          error=CheckMinLength(which,tempobj,field_name);
          if (error>0) break;             
          error=CheckMaxLength(which,tempobj,field_name);
          if (error>0) break;
          error=CheckNumValue(which,tempobj);
          if (error>0) break;                
          error=CheckEmail(which,tempobj,field_name);
          if (error>0) break;                
          error=CheckPassword(which,tempobj,field_name);                
          if (error>0) break;
          error=CheckInfimum(which,tempobj,field_name);                
          if (error>0) break;
          error=CheckSupremum(which,tempobj,field_name);                
          if (error>0) break;                                          
        }
    }
 if (error>0) 
    {
     if (which.elements["title_"+field_name])
         {
          field_title=which.elements["title_"+field_name].value.toUpperCase();
         } 
     else field_title=field_name.toUpperCase();   
     error_message='Field "'+field_title+'" ';
     switch (error)
            {
             case 1: error_message+="is mandatory";                                         ; break;  
             case 2: error_message+="must consist of at least "+display+" symbols"          ; break;
             case 3: error_message+="must not contain more than "+display+" symbols"        ; break;
             case 4: error_message ="The characters of national alphabets are inadmissible.\n" +
                                    error_message + "cannot contain '"+display+"' at position "+display_pos ; break;
             case 5: error_message+="must contain a number"                                 ; break;
             case 7: error_message ="Password confirmation failed"                          ; break;
             case 8: error_message+="cannot be less than "+display                          ; break;
             case 9: error_message+="cannot be more than "+display                          ; break;
             case 10: error_message+="cannot contain "+display+" symbol"                    ; break;
            } 
     if (error!=6) alert(error_message);
     which.elements[i].focus();
     return 0;
    }
 else
    {
     for (i=0;i<which.length;i++) ReplaceForbiddenSymbols(which,which.elements[i]); 
     return 1;
    } 
 return 0;   
}
//******************************************************************************
function CheckRequiredField(which,el,el_name)
{
 var error=0;
 var el_name;
 var min_value;

 if (el.name.indexOf("required_") ==-1)
     {
      return 0; 
     } 
 switch (el.type)
        {
         case "text":     
         case "textarea":
         case "password":
         case "file": 
              if (trim(el.value)=="") return 1;
              break;
        }
  if (el.type.substring(0,6)=="select" &&  el.options[el.options.selectedIndex].value==0 ) 
      return 1; 
 return 0;       
}
//******************************************************************************
function CheckForbiddenSymbols(which,el)
{
 var error=0, fsym=new Array("<script","<style","/style>","/script>");
 if (!(el.type=="text" || el.type=="textarea" || el.type=="file"  || el.type=="password" )) return 0;
 for (var i in fsym)     
     {
      if (el.value.indexOf(fsym[i])>-1)
         {
          error=4;
          display=fsym[i];
          break;
         }
     } 
 for (i=0;i<el.value.length;i++)
     {
      if ( el.value.charCodeAt(i)>128)
         {
          error=4;
          display=el.value.charAt(i);
          display_pos=i+1;
          break;
         }               
     }   
 if (el.type=="file" && el.value.indexOf("'")>-1)         
    {
     error=4;
     display="'";
    }
 if (el.type=="file" &&  el.value.indexOf('"')>-1)         
    {
     error=4;
     display='"';
    }    
 return error;
}
//******************************************************************************
function ReplaceForbiddenSymbols(which,el)
{
 var error=0,pos=-1, 
     fsym=new Array("'","\""); //replaces of ' and " are needed
     var rsym=new Array("`","`");
 if ( !(el.type=="text" || el.type=="textarea" || el.type=="file"  || el.type=="password" )
     || el.name.substr(0,5)=="asis_"
    ) return 0;
 for (var i in fsym)     
     {
      pos=el.value.indexOf(fsym[i]);
      while (pos>-1)
         {
          error=4;
          //display=fsym[i];
          //break;
          el.value=el.value.substring(0,pos)+rsym[i]+el.value.substr(pos+1);
          pos=el.value.indexOf(fsym[i]);
         }
     }    
 return error;
}
//******************************************************************************
function CheckMinLength(which,el,el_name)
{
 if (!which.elements["min_"+el_name]) return 0;
 min_value=parseInt(which.elements["min_"+el_name].value);
 if (min_value>el.value.length) 
    {
     display=min_value;
     return 2;
    }
 return 0;
}
//******************************************************************************
function CheckMaxLength(which,el,el_name)
{
 var error=0,el_name;
 if (el.type!="text" && el.type!="textarea" && el.type!="file" && el.type!="password" ) return 0; 
 if (which.elements["max_"+el_name])
    max_value=parseInt(which.elements["max_"+el_name].value);
 else 
    {
     if (el.maxLength)
        max_value=parseInt(el.maxLength);
     else
        {
         if (el.size)
            max_value=parseInt(el.size);
         else
            max_value=0;   
        } 
    }    
 if (max_value && max_value<el.value.length) 
    {
     error=3;                                                        
     display=max_value;
    } 
 
 return error;
}
//******************************************************************************
function CheckNumValue(which,el,el_name)
{
 var el_name1="";

 if (el.type!="text") return 0; 
 if (el.value=="" || el.value==" ") return 0; 
 if (el.name.substring(0,9)=="required_") el_name1=el.name.substr(9);
 else el_name1=el.name;
 if (el_name1.substring(0,4)!="num_") return 0; 

 if (isNaN(parseInt(el.value))) return 5;   
 el.value = parseInt(el.value)
 if (which.elements["sup_"+el_name] && which.elements["sup_"+el_name].value<el.value) 
    {
     display=which.elements["sup_"+el_name].value;
     return 8; 
    } 
 if (which.elements["inf_"+el_name] && which.elements["inf_"+el_name].value>el.value)
    {
     display=which.elements["inf_"+el_name].value;
     return 9; 
    } 
 return 0; 
}
//******************************************************************************
function CheckEmail(which,el,el_name)
{
 var error=0;
 if (el.type!="text" || el_name!="email" || el.value=="") return 0;
 if (!emailCheck(el.value)) error=6;
 return error;
}
//******************************************************************************
function CheckPassword(which,el,el_name)
{
 if (el.type!="password" || el_name=="password") return 0;
 if (el.value!=which.elements["required_password"].value)
    return 7;
 return 0;   
}
//******************************************************************************
function GetFieldName(name)
{
 var str="";
 
 str=name;
 if (str.substring(0,9)=="required_")
    str=str.substr(9);
 if (str.substring(0,4)=="num_")
    str=str.substr(4);    

 return str;
}
//******************************************************************************
function CheckInfimum(which,el,el_name)
{
 if (!which.elements["inf_"+el_name]) return 0;
 inf_value=parseInt(which.elements["inf_"+el_name].value);
 if (inf_value>el.value) 
    {
     display=inf_value;
     return 8;
    }
 return 0;
}
//******************************************************************************
function CheckSupremum(which,el,el_name)
{
 if (!which.elements["sup_"+el_name]) return 0;
 sup_value=parseInt(which.elements["sup_"+el_name].value);
 if (sup_value<el.value) 
    {
     display=sup_value;
     return 9;
    }
 return 0;
}
//******************************************************************************
function emailCheck (emailStr) 
{
 // The following pattern is used to check if the entered e-mail address fits the user@domain format.  
 // It also is used to separate the username from the domain. 
 var emailPat=/^(.+)@(.+)$/
  
 // The following string represents the range of characters allowed in a username or domainname.  
 var validChars="[a-zA-Z0-9\\-\\_]";
 
 // The following pattern applies if the "user" is a quoted string (in which case, there are 
 // no rules about which characters are allowed and which aren't; anything goes).  
 // E.g. "jiminy cricket"@disney.com is a legal e-mail address. 
 var quotedUser=/(\"[^\"]*\")/
 
 // The following pattern applies for domains that are IP addresses,
 // rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
 // e-mail address. NOTE: The square brackets are required. 
 var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
 
 // The following string represents an atom (basically a series of
 // non-special characters.) 
 var atom=validChars + '+'
 
 // The following string represents one word in the typical username.
 // For example, in john.doe@somewhere.com, john and doe are words.
 // Basically, a word is either an atom or quoted string. 
 var word="(" + atom + "|" + quotedUser + ")"
 // The following pattern describes the structure of the user
 var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
 
 // The following pattern describes the structure of a normal symbolic domain, as opposed to ipDomainPat, shown above. */
 var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

// Begin with the coarse pattern to simply break up user@domain into different pieces that are easy to analyze. 
var matchArray=emailStr.match(emailPat)
if (matchArray==null) 
   {
    // Too many/few @'s or something; basically, this address doesn't
    // even fit the general mould of a valid e-mail address. 
  alert("Email address seems incorrect");
  return 0;
   }
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 

if (user.match(userPat)==null) 
   {
    // user is not valid
    alert("The email address doesn't seem to be valid.");
    return 0;
   }

// if the e-mail address is at an IP address (as opposed to a symbolic host name) make sure the IP address is valid. 
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) 
   {
    // this is an IP address
  for (var i=1;i<=4;i++) 
      {
       if (IPArray[i]>255) 
          {
           alert("Destination IP address is invalid!");
         return 0;
          }
        }
    return 1;
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) 
   {
  alert("The domain name doesn't seem to be valid.");
    return 0;
   }

// domain name seems valid, but now make sure that it ends in a three-letter word (like com, edu, gov) 
// or a two-letter word, representing country (uk, nl), and that there's a hostname preceding the domain or country. 

// Now we need to break up the domain to get a count of how many atoms it consists of. 
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || domArr[domArr.length-1].length>3) 
   {
    // the address must end in a two letter or three letter word.
    alert("The address must end in a three-letter domain, or two letter country.");
    return 0;
   }

// Make sure there's a host name preceding the domain.
if (len<2) 
   {
    var errStr="This address is missing a hostname!";
    alert(errStr);
    return 0;
   }

 // If we've gotten this far, everything's valid!
 return 1;
}

//******************************************************************************
function ValidateFormName(FormName)
{
 var which;
 which=document.forms[FormName];
 ValidateForm(which);
 return;
}
//******************************************************************************
function isEmail(s)
{  
 var intFlag; 
 if (window.RegExp) 
    {
     var reg1str = "(\\s)|(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)|(^_+@)|(^\\-+@)";
     var reg2str = "^[\\w\\.\\-]+@((\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)|[a-zA-Z0-9\\-]{2,})$";
     var reg1 = new RegExp(reg1str);
     var reg2 = new RegExp(reg2str);
     if (!reg1.test(s) && reg2.test(s))
         intFlag = 1;
     else    
         intFlag = 0;
   } 
 else 
   {
    if(str.indexOf("@") >= 0)
       intFlag = 1;
    else intFlag = 0;
  }
 if (!intFlag) alert("The email address doesn't seem to be valid.");
 return intFlag; 
}  

/*  functions that validate project dates input */
//****************************************************************************************
function validDigit(e)
{
// validates if symbolNum is number of digit. Uses to restrict non digital input in number fields.
// 48 - number of zero; 57 - number of 9
    
 var whichCode;
  
  if (NN)
  {
    whichCode = e.which;
  }
  else if (IE && e.type == "keypress")
  {
    whichCode = e.keyCode
  }
  return ( whichCode >= 48 && whichCode <= 57 );
}

//******************************************************************************
function mkDateFromGroup(formObj, groupName)
{
    var temDate;
    with (formObj)
    {
        yearVal = parseInt( eval("num_" + groupName + "_year.value") );
        monthVal = parseInt( eval(groupName + "_month.options[" + groupName + "_month.selectedIndex].value") );
        dateVal = parseInt( eval("num_" + groupName + "_date.value") );
        if ( isNaN(yearVal) || yearVal<yMin || yearVal>yMax )
        {
            alert("You've set year incorrectly.\nIt mustn't be empty, it must be numeric,\nit must be greater than " + (yMin-1) + " and less than " +(yMax+1));
            eval("num_" + groupName + "_year.focus(); num_" + groupName + "_year.select();");
            return -1;
        }
        
        if ( !isNaN(dateVal) )
        {
            tmpDate = new Date(yearVal, monthVal, dateVal);
        }

        if ( isNaN(dateVal) || !(tmpDate.getMonth() == monthVal && tmpDate.getDate() == dateVal) )
        {
            alert("You've set day incorrectly.\nIt mustn't be empty, it must be numeric,\nit must be greater than 0  and not greater than number of days in " + eval(groupName + "_month.options[" + groupName + "_month.selectedIndex].text") + " in " + yearVal + " year." );
            eval("num_" + groupName + "_date.focus(); num_" + groupName + "_date.select();");
            return -1;
        }
        else 
        {
           return tmpDate.getTime();
        }
    }
}

//******************************************************************************
function checkPrjDates(formObj)
{
    var startDate = mkDateFromGroup(formObj, "start");
    if (startDate < 0) return 0;

    var endDate = mkDateFromGroup(formObj, "end");
    if (endDate < 0) return 0;
    
    var actualDate = mkDateFromGroup(formObj, "actual");
    if (actualDate < 0) return 0;
    
    if  (startDate <= endDate && endDate <= actualDate)
    {
        return 1;
    }
    else
    {
        alert("Project Start Date must be less than its Scheduled Finish.\nProject Sheduled Finish must be less than its Actual Finish.");
        return 0;            
    }
}
//************************************************************************************
function trim(s)
{
 s=s.replace(/^([\s]+)/,"");
 s=s.replace(/([\s]+)$/,"");
 return s;
} 