//=========================================================================//
// Author: 	Michelle Farrell
// Date Created:   	30-Jun-2004
// 
// Details: 	Javascript include file contains validation functions for
// 		date being submitted through the different forms.
// 
// Last Modified:     18-Aug-2004
//
 //=========================================================================//

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
 
function Validate_N(form)
//=========================================================================//
// Validate the news details entered
//=========================================================================//
{
	if(!checkNotNull(form.txtOption,"an option. F for Feature or N for News"))
      		return;
          		
	if(!checkNotNull(form.txtHeadline,"a Headline"))
          		return;
          	if(!checkNotNull(form.txtareaPara1,"a story"))
          		return;
          	if(!checkNotNull(form.txtareaPara2,"a paragraph"))
          		return;
      		
	form.submit();
}



function IsValidTime(timeStr) 
//=========================================================================//
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.
//=========================================================================//
{

var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

var matchArray = timeStr.match(timePat);
if (matchArray == null) {
	alert("Time is not in a valid format.");
return false;
}
hour = matchArray[1];
minute = matchArray[2];
second = matchArray[4];
ampm = matchArray[6];

if (second=="") { second = null; }
if (ampm=="") { ampm = null }

if (hour < 0  || hour > 23) {
alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
return false;
}
if (hour <= 12 && ampm == null) {
if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
alert("You must specify AM or PM.");
return false;
   }
}
if  (hour > 12 && ampm != null) {
alert("You can't specify AM or PM for military time.");
return false;
}
if (minute<0 || minute > 59) {
alert ("Minute must be between 0 and 59.");
return false;
}
if (second != null && (second < 0 || second > 59)) {
alert ("Second must be between 0 and 59.");
return false;
}
return false;
}

function Validate_B(form)
//=========================================================================//
// Validate the booking details
// Referenced in b_action.asp
// Checks that the day selected and the day of the start date match and that a start time and end time are
// entered. 
// ** Need to add in time validation function
//=========================================================================//
{

var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")	
	
var mmddyy = new Date(form.txtStarting_date.value);

var day=mmddyy.getDay()
day_picked= dayarray[day]

DayInteger=form.sltday_of_week.selectedIndex
sTimeInteger=form.sltTimeFrom.selectedIndex
eTimeInteger=form.sltTimeto.selectedIndex

var day_of_week = form.sltday_of_week[DayInteger].value
var start_time     = form.sltTimeFrom[sTimeInteger].value
var end_time     = form.sltTimeto[eTimeInteger].value



startt=start_time.substring(0,2)
endt=end_time.substring(0,2)

  if (parseInt(startt) >= parseInt(endt))
  	{
     	alert("The Start Time cannot be less/equal then the end time")
     	return;
     	}
     	
   if(!checkNotNull(form.txtStarting_date,"a start date"))
   	return; 
          	
   if(day_of_week != day_picked)
              {
             	alert("Start day does not equal day of week selected. Please check your dates") 	
             	form.sltday_of_week.focus()
	return
             }	
   //----------------------------------------------------------------------------------
   

form.submit()
}


function Validate_Group(form)
//=========================================================================//
// Validate the Booking
// Referenced in b_bookaroom.asp
// If the group already exists, we just need to validate the booking which we already are doing in validate_b
//=========================================================================//
{
if(form.register.value=="False")
//if the group is not registered no need to check all these details
{   
             CountInteger=form.sltMain_aim.selectedIndex
             var main_aim_val = form.sltMain_aim[CountInteger].value;
             
             GInteger=form.sltGroup_affiliated.selectedIndex
             var group_affiliated_val = form.sltGroup_affiliated[GInteger].value;
             
                         
            // Check that Contact Name is not empty
             //if(!checkNotNull(form.txtEntered_By,"a Contact name"))
          	//return;
           
            // Check that Group Name is not empty
             if(!checkNotNull(form.txtGname,"a Group name"))
          	return;
            
            // Check that Purpose field is not empty
          /* if(!checkNotNull(form.txtareaPurpose,"the purpose of group/organisation"))
          	return;
               
             // Check that Postal field is not empty
             if(!checkNotNull(form.txtareaPostal,"a Postal Address"))
          	return;  
          	
               //Check that phone is not empty  and is valid
               if(!checkNotNull(form.txtPhone_w,"a phone number"))
                  	return;
              else if (!validnum(form.txtPhone_w,"phone numer. Numbers only"))
          	return false;
             
             //Check that mobile phone is not empty and is valid
               if(!checkNotNull(form.txtPhone_m,"a mobile phone number"))
                   	return;
              else if (!validnum(form.txtPhone_m,"mobile phone numer. Numbers only"))
          	return false;
             
           // Check that email address field is not empty and is valid
             if(!checkNotNull(form.txtEmail,"an email address"))
          	return;  
             else if(!validEmail(form.txtEmail.value))
             	return;
             
            // Check that Website field is not empty
            if(!checkNotNull(form.txtWeb,"a website address"))
          	return;	
           // Check that Location field is not empty
             if(!checkNotNull(form.txtLoc,"a location"))
         	return;
          // Check that description field is not empty
             if(!checkNotNull(form.txtareaDesc,"a description"))
          	return;
           
             // Check that a role has been selected 
              if(main_aim_val=="-1")
              {
             	alert("Please select a role") 	
             	form.sltMain_aim.focus()
             	return false;
             }
             // Check that the qualifications field is not empty
              if(!checkNotNull(form.txtareaQualifications,"qualifications/training"))
          	return;
          
            // checks value of radio buttons
            for (i=0;i<document.forms[0].rdoAffiliated.length;i++)
            {
          	if (document.forms[0].rdoAffiliated[i].checked)
          	{
          		user_input = document.forms[0].rdoAffiliated[i].value;
          	}
            }
          
             // Check that if group affiliated is selected, a group name is selected
              if(user_input!=0)
             	{
             		if(group_affiliated_val==-1)
             		{
             			alert ("Please select the group you are affilated to")
             			form.sltGroup_affiliated.focus()
             			return false;
             		
             		}
             	}
	*/
 	
	 //Check that a day of the week matches the start date day selected
	form.submit()
  } 
   
   else
   {
   Validate_B(form)	
   }
}


function Validate_EventDetails(form)
//=========================================================================//
// Validate the Event Details Entered
// Referenced in pp_addlisting.asp
// If the group already exists, we just need to validate the event details which we already are doing in validate_b
//=========================================================================//
{

if(form.register.value=="False")
//if the group is not registered no need to check all these details
{   
                         
            // Check that Contact Name is not empty
             //if(!checkNotNull(form.txtEntered_By,"a Contact name"))
          	//return;
           
            // Check that Group Name is not empty
             if(!checkNotNull(form.txtGname,"a Group name"))
          	return;
            
            Validate_B(form)	
             //Check that a day of the week matches the start date day selected
	
  } 
    else
   {
   Validate_B(form)	
   }
}

function Validate_Vol(form)
//=========================================================================//
// Function Used to check all the fields in the volunteer form before it is submitted
// Referenced in volunteer.asp
//=========================================================================//

{
	
   form.submit();
   return;
}


function Validate_Rooms(form)
//=========================================================================//
// Function used in the Rooms Submission section for validation
// Referenced in r_action.asp
// ** Need to double check required fields
//=========================================================================//

{

  //aval=form.txtAval.value.toUppercase()
  //alert(aval.value)
  
   // Check that Room Name is not empty
   if(!checkNotNull(form.txtName,"a Room name"))
	return;
     

   //Check that Price is not empty and contains valid price
   //if(!checkNotNull(form.txtPrice,"a price"))
   //	return;
    //else if (!validnum(form.txtPrice,"price."))
//	return false;
       //Check that avaliable is not empty
    //if(!checkNotNull(form.txtAval,"availibility"))
    //	return;
       
   //Check that image path is not empty
    //if(!checkNotNull(form.txtImg_p," an image name"))
      //	return ;
   
     //Check that capacity is not empty
     //if(!checkNotNull(form.txtCap,"a capacity"))
        // 	return;
    //else if (!validnum(form.txtCap," capacity."))
      //	return false;
   
   form.submit();
   return;
	
}

function Validate_Link(form)
//=========================================================================//
// Function used in the locations Submission section for validation
// Referenced in l_action.asp
// ** Need to double check required fields
//=========================================================================//

{
           CatInteger=form.sltLink_Cat.selectedIndex
           var cat_l_val = form.sltLink_Cat[CatInteger].value;
    	
  
   // Check that URL is not empty
   if(!checkNotNull(form.txtURL,"a URL"))
	return;
   // Check a category is selected
    if(cat_l_val==-1)
   		{
   			alert ("Please select a category")
   			form.sltLink_Cat.focus()
   			return false;
   		}

   form.submit();
   return;
	
}




function Validate_Loc(form)
//=========================================================================//
// Function used in the locations Submission section for validation
// Referenced in l_action.asp
// ** Need to double check required fields
//=========================================================================//

{
  
   // Check that Location Name is not empty
   if(!checkNotNull(form.txtName,"a Location name"))
	return;
     

   form.submit();
   return;
	
}


function validprice(Obj,txt)
//=========================================================================//
// Function to validate price entered in a form field
// Referenced in volunteer.asp
//=========================================================================//

{
   var nstr="0123456789."
   
   for(var i=0;i<Obj.value.length;i++){
   	var cc=Obj.value.substring(i, i+1)
      for(var j=0;j<nstr.length;j++){
		var isvalid=false;
      	var dd = nstr.substring(j,j+1)
         	if(cc == dd){
            	isvalid = true;
            	break;
            }
      }
	if(isvalid==false)
	{
		alert("Please enter a valid "+ txt);
		Obj.focus();
		return false;
	}
   }
   return true;
} 
 
function validnum(Obj,txt)
//=========================================================================//
// Ensures leters are not entered into a numbers field
//=========================================================================//

{
   var nstr="0123456789- ()"
   
   for(var i=0;i<Obj.value.length;i++){
   	var cc=Obj.value.substring(i, i+1)
      for(var j=0;j<nstr.length;j++){
		var isvalid=false;
      	var dd = nstr.substring(j,j+1)
         	if(cc == dd){
            	isvalid = true;
            	break;
            }
      }
	if(isvalid==false)
	{
		alert("Please enter a valid "+ txt);
		Obj.focus();
		return false;
	}
   }
   return true;
} 

function checkNotNull(obj, txt)
//=========================================================================//
// Checks for no data and alerts user to enter data
//=========================================================================//

{	
	var str = obj.value;
	if(str.length ==0 || str == -1)
	{
		alert("Please enter " + txt + ".");
		obj.focus();
		return false;		
	}
	
	return true;
}



function validEmail(emailStr) {
//=========================================================================//
// Validates email address checking for the presence of the @ symbol, etc
//=========================================================================//
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
	alert("Please enter a valid email address")
	return
}


var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
    alert("The username in your E-Mail address is invalid.")
    return
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("The destination IP address in your E-Mail is invalid")
		return
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name in your E-Mail address is invalid.")
    return
}

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 E-Mail address must end in a three-letter domain, or two letter country.")
   return
}

if (len<2) {
   var errStr="This E-Mail address is missing a hostname"
   alert(errStr)
   return
}
if (!checkemailchars(emailStr)){
alert('Please enter valid characters in your E-Mail address')
return
}
return true;
}

function checkemailchars(Obj){
   var nstr="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_@.1234567890-"
   
   for(var i=0;i<Obj.length;i++){
   	var cc=Obj.substring(i, i+1)
      for(var j=0;j<nstr.length;j++){
		var isvalid=false;
      	var dd = nstr.substring(j,j+1)
         	if(cc == dd){
            	isvalid = true;
            	break;
            }
      }
	if(isvalid==false)
		return false;
   }
   return true;
}

function Validate_Group_Check(form)
//=========================================================================//
// If Yes is selected, the user has to select a group to continue
// // Referenced in b_check.asp
//=========================================================================//{
{	
   
   gInteger=form.sltGroup_Name.selectedIndex
   var group_val = form.sltGroup_Name[gInteger].value;
   

    // checks value of radio buttons
  for (i=0;i<document.forms[0].rdoRegistered.length;i++)
  {
	if (document.forms[0].rdoRegistered[i].checked)
	{
		user_input = document.forms[0].rdoRegistered[i].value;
	}
  }

   // Check that user selects that group is already registered, they select a group
    if(user_input!=0)
   	{
   		if(group_val==-1)
   		{
   			alert ("Please select a group")
   			form.sltGroup_Name.focus()
   			return false;
   		}
   	
   	}
  
   form.submit();
   return;
}

