/*
  FUNCTION LIST : 

    CheckEmailAddresses()             ::
    Characters_left()                 ::
    Message_Check()                   ::
    VerifyEmailSend()                 ::
    CheckSMSNumbers
    VerifySMSSend
    InTouch_Login
    ValidateCreateUserForm
    Email_Reset_Password
    ValidateAddGroup
    GroupAddContact
    ShowGroupDetails
    GroupListRedirect
    GoTo_UserList
    GoTo_AddGroup
    Edit_Group
    ConfirmGroupEdit
    ConfirmGroupDelete
    AddKeyListerner
    ValidateImport
    ValidateFileName
    CreateContact
    EditContact
    DeleteGroupContact
    ConfirmContactEdit
    DeactivateRecipient
    ReactivateRecipient
    AddAdHocContact
    RemoveAdHocRecipient
    GroupRecipientSelect
    AddRecipientGroup
    RemoveRecipientGroup
    ContactSearch
    SelectGroup
    AllRecipientGroupSelect

    LoadGroupContacts()
    
*/

/*************************************************************************** */ 
function ValidateCellphoneNumberField(field_id)
{
   var errmsg = "";
   
   return_value = "";
   if ($(field_id))
        {
         check_value = trim($(field_id).value);
         check_value = check_value.replace(/\s/gi,"");

         check_pass = false;
         
         switch(check_value.substring(0,1))
            {
                case "0":
                    if (check_value.match(/^08[2347][\d+]{7}/)
                        || check_value.match(/^07[1234689][\d+]{7}/)
                        )
                        {
                         check_pass = true;
                        }
                        else
                        {
                         errmsg += "Mobile number provided is incorrect, please correct";
                        }
                    break;
                    
                case "+":
                    if (check_value.match(/^\+27[8][2347][\d+]{7}/)
                        || check_value.match(/^\+27[7][1234689][\d+]{7}/) )
                        {
                            check_pass = true;
                        }
                        else
                        {
                         errmsg += "Mobile number provided is incorrect,please correct";
                        }
                    break;
                
                case "":
                    errmsg += "Please provide a mobile number \n";
                    check_pass = false;
                    break;
                
                                    
                default:
                    errmsg += "Mobile numbers have to start with either 08/07 or +27";
                    break;
            }
         
         if (!check_pass)
            {
             //errmsg += "Please provide a valid mobile number";
             return_value = false;
            }
            else
            {
             return_value = true;
            }
        }
   return return_value;
}//function ValidateCellphoneNumberField(field_id)
/*************************************************************************** */ 
function ValidateEmailField(field_id)
 {
    return_value = "";
    
    if ($(field_id))
        {
            check_value = trim($(field_id).value);
            
            if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
            ||  check_value.indexOf("@") == -1
            ||  check_value.indexOf("..") != -1
            ||  check_value.length == 0
            )
            {
              return_value = false;  
             //errmsg += "Please provide a valid email address \n";
            }//if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
            else
                {
                return_value = true;
                }//if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
        }
    return return_value; //false : not a valid email ; true : valid email
 }//function ValidateEmail(field_id)
/*************************************************************************** */ 
function dump(arr,level) {
    var dumped_text = "";
    if(!level) level = 0;
    
    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";
    
    if(typeof(arr) == 'object') { //Array/Hashes/Objects 
        for(var item in arr) {
            var value = arr[item];
            
            if(typeof(value) == 'object') { //If it is an array,
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            } else {
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    return dumped_text;
}//function dump(arr,level) {
/*************************************************************************** */

function print_r(theObj)
    {
      if(theObj.constructor == Array ||
         theObj.constructor == Object)
       {
        document.write("<ul>")
        
        for(var p in theObj)
        {
          if(theObj[p].constructor == Array||
             theObj[p].constructor == Object)
             {
                document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
                document.write("<ul>")
                print_r(theObj[p]);
                document.write("</ul>")
                }
             else 
             {
                document.write("<li>["+p+"] => "+theObj[p]+"</li>");
             }
        }
        document.write("</ul>")
      }
    }//function print_r(theObj)


/*
trim : 
Used to trim (remove the whitespaces on the edges of words

IN : stringToTrim : String value you would like to remove possible whitespaces from the edges off
      
OUT : output is the string sent in without any whitespaces on the sides

*/
function trim(stringToTrim) 
{
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}//function trim()

/*************************************************************************** */

function CheckEmailAddresses(email_field)
{
  
  var output = "";
  
  if ($(email_field))
    {
      var email_array_count_comma = $(email_field).value.split(',').count;
      var email_array_count_semicolon = $(email_field).value.split(';').count;
      var email_array = new Array();
      
      //IF THE DELIMETER THAT WAS USED = ,
      if (email_array_count_comma > email_array_count_semicolon)
        {
            email_array = $(email_field).value.split(',');
        }
        else //IF THE DELIMETER THAT WAS USED = ;
        {
            email_array = $(email_field).value.split(';')
        }
    }

    
  
    if (email_array.length > 0 && email_array[0] != "")
    {
        //Email recipients found, do standard email check ( according to database contraint )
       var email_error_found = false;
       for(intCount=0;intCount < email_array.length; intCount++)
       {
        email_array[intCount] = trim(email_array[intCount]);
        if (!email_array[intCount].match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) 
            && !email_error_found)
            {
             output += "An email address provided is invalid please correct \n";
             
             //DO SELECTION OF EMAIL ADDRESS INSIDE OF FIELD
            
            
            
            $(email_field).value.indexOf(email_array[intCount]);
            $(email_field).value.selectionEnd = $(email_field).value.indexOf(email_array[intCount]) + email_array[intCount].length;
            email_error_found = true;
            }
       } 
    }
    else
    {
     output += "Please provide email recipients \n";
    }
  
  return output;
}

/*************************************************************************** */
function Characters_left(value_control,max, update_control)
{
    var char_left = 0;

    char_left = parseInt(max - value_control.value.length);
    
    if ($(update_control))
        {
         $(update_control).value = char_left;
        }
    
    CheckMessageStatus();
        
    return char_left;
    
}//function Message_Check(value,max)

/*************************************************************************** */
function Message_Check(value_control,max,update_control)
{
 var char_left2 = 0;
 
 char_left2 = Characters_left(value_control,max,update_control);
 
 if (char_left2 < 0 )
 {
  //alert('Maximum characters reached');
  if ($(value_control))
    {
     var string_interm = ""+ $(value_control).value;
     $(value_control).value = string_interm.substring(0,max);
    }
 }
 
 else
 {
  if ($(value_control).value % 10 == 0)
  {
   //alert($(value_control).value);
  }
 }
 
}//function Message_Check(value_control,max,update_control)

/*************************************************************************** */
function VerifyEmailSend(form_id,email_address_to_field)
{
    
    var errmsg = "";
    
    //errmsg += CheckEmailAddresses(email_address_to_field); - old way where the TO field was in the page
    
    
    //Check if any adhoc or groups have been selected
    //alert("group_selected" + group_selected  + "::" + "contacts_selected::" + contacts_selected);
 if (!group_selected && !contacts_selected)
    {
      errmsg += "Please select either a group or add an Ad hoc recipient \n";
    }
    /*
    if (!contacts_selected)
        {
        errmsg += "Please provide recipients for this message \n";
        }
    */
    
    if ($('msg_subject'))
        {
         if ($('msg_subject').value.length <= 0)
            {
             errmsg += "Please provide a subject for the email \n";
            }
        }
    
    if ($('msg_body'))
        {
         if ($('msg_body').value.length <= 0)
            {
             errmsg += "Please provide an email message to be sent \n";
            }
        }
    
    if (errmsg  == "")
        {
            if ($('send_body'))
            {
             $('send_body').setStyle('cursor','wait');
            }
            
            if ($('btnSendEmail'))
            {
             $('btnSendEmail').setStyle('cursor','wait');
            }
            
            if ($(form_id))
            {
             $(form_id).submit();
            }
        }
        else
        {
            if ($('send_body'))
            {
             $('send_body').setStyle('cursor','pointer');
            }        

            if ($('btnSendEmail'))
            {
             $('btnSendEmail').setStyle('cursor','pointer');
            }

        
         alert(errmsg);
        }
}//function VerifyEmailSend(form_id,email_address_to_field)

/*************************************************************************** */
function CheckSMSNumbers(sms_to_field)
{
    var output = "";
    var sms_array = new Array();
    
    if ($(sms_to_field))    
    {
     sms_comma_array_count = $(sms_to_field).value.split(',').length;
     sms_semi_colon_array_count = $(sms_to_field).value.split(';').length;
     
     if (sms_comma_array_count > sms_semi_colon_array_count)
        {
         sms_array = $(sms_to_field).value.split(',');
        }
        else
            {
                sms_array = $(sms_to_field).value.split(';');
            }
    
    if (sms_array.length > 0 
        && sms_array[0] != "")
        {
          sms_recipient_error_found = false;
          
          for (intCount=0;intCount < sms_array.length;intCount++)
          {
          sms_array[intCount] = trim(sms_array[intCount]);
          /*
          alert(!isNaN(sms_array[intCount]));
          alert(sms_array[intCount].length != 10);
          alert(!sms_recipient_error_found);
          */
          if (sms_array[intCount] != "")
          {
              if ( 
                    (isNaN(sms_array[intCount]) || sms_array[intCount].length != 10 )
                    && !sms_recipient_error_found)
                    {
                     output += "A sms recipient number is invalid. Please correct \n";
                     sms_recipient_error_found = true;
                    }
              }
          }
        }
        else
        {
         output += "Please provide sms recipients \n";
        }
    
    }
    
    


   return output;
}//function CheckSMSNumbers(sms_to_field)


/*************************************************************************** */
function VerifySMSSend(form_id,sms_to_field)
{
 var errmsg = "";
 
 
 //alert($('Group_Recipients').getElements('input[name$=_GroupCheck]').length);
 //errmsg += CheckSMSNumbers(sms_to_field);
 
  if (!group_selected && !contacts_selected)
    {
      errmsg += "Please select either a group or add an Ad hoc recipient \n";
    }
    
 if ($('message'))
    {
     if ($('message').value.length == 0)
        {
         errmsg += "Please provide a message to send to the recipients \n";
        }
    }
 
 
 if (errmsg == "")
    {
            if ($('send_body'))
            {
             $('send_body').setStyle('cursor','wait');
            }
            
            if ($('btSendSMS'))
            {
             $('btSendSMS').setStyle('cursor','wait');
            }


     if ($(form_id))
        {
          $(form_id).submit();
        };
    }
    else
    {
            if ($('send_body'))
            {
             $('send_body').setStyle('cursor','pointer');
            }
            
            if ($('btSendSMS'))
            {
             $('btSendSMS').setStyle('cursor','pointer');
            }     
     alert(errmsg);
    }


}//function VerifySMSSend(form_id,sms_to_field)
/*************************************************************************** */

function InTouch_Login(form_id)
{
  var errmsg = "";
  
  if ($('username'))
    {
     if ($('username').value.length == 0)
     {
      errmsg += "Please provide a username \n";
     }
    
    }

   if ($('password'))
    {
     if ($('password').value.length == 0)
     {
      errmsg += "Please provide a password \n";
     }
    
    }

  if (errmsg == "")
    {
        if ($(form_id))
        {
            $(form_id).submit();
        }
    }
    else
    {
    
     alert(errmsg);
    }


}//function InTouch_Login(form_id)
/*************************************************************************** */


function ValidateCreateUserForm(form_id)
{
 var errmsg = "";

 
 //CHECK THAT FIRST NAME NOT BLANK
 if ($('user_firstname'))
    {
     check_value = trim($('user_firstname').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Firstname for the user \n";
     }
    
    }
 
 //CHECK THAT LASTNAME NOT BLANK
 if ($('user_lastname'))
    {
     check_value = trim($('user_lastname').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Last Name for the user \n";
     }
    
    }

 //CHECK THAT LANGUAGE HAS BEEN SELECTED
 if ($('user_language'))
    {
     check_value = trim($('user_language').value)
     if (check_value.length == 0)
     {
      errmsg += "Please select a language for the user \n";
     }
    
    } 
 
 //CHECK THAT PASSWORD FIELD HAVE BEEN FILLED IN, IF SO, CHECK ACCORDING TO SPECIFICS PROVIDED
 //HAS TO BE 6 CHARS LONG, HAS TO HAVE BOTH charators and numbers in it
 password_pass_check = true;
 if ($('user_password'))
    {
     check_value = trim($('user_password').value);
     
     if (check_value.length == 0)
        {
         errmsg += "Please provide a password for the user \n";
         password_pass_check = false;
        }
        else if (check_value.length < 6)
        {
         errmsg += "Please provide password [minimum 6 charactors please] \n";
         password_pass_check = false;
        }
            else
            {
                //CHECK THAT PASSWORD HAS BOTH CHARS AND NUMBERS IN
                if (!isNaN(check_value))
                    {
                     errmsg += "Please include letters in your password as well \n";
                     password_pass_check = false;
                    }
                
                //CHECK THAT THERE ARE NUMBERS IN THE PASSWORD
                if (!check_value.match(/\d+/gi))
                    {
                     errmsg += "Please include numbers in your password \n";
                     password_pass_check = false;
                    }
            }
      
    }
 
 //CHECK THAT THE CONFIRM PASSWORD LOOKS THE SAME AS THE PASSWORD FIELD
 if ($('user_password_confirm') && password_pass_check)
    {
     check_user_password_value1 = trim($('user_password').value);
     check_user_password_value2 = trim($('user_password_confirm').value); 
     if (check_user_password_value1 != check_user_password_value2) 
        {
         errmsg += "Confirmation password not the same as provided password \nPlease correct either\n";
        }
    
    }
 
 //CHECK FOR EMAIL ADDRESS IN THE EMAIL FIELD

    if ($('user_email'))
        {
            check_value = trim($('user_email').value);
            
            if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
            ||  check_value.indexOf("@") == -1
            ||  check_value.indexOf("..") != -1
            ||  check_value.length == 0
            )
            {
             errmsg += "Please provide a valid email address \n";
            }
        }
        
    //CHECK FOR MOBILE NUMBER ( CELL NUMBER ) AND THEN CHECK ACCORDING TO DATABASE CONTRAINTS
    if ($('user_cell_phone_number'))
        {
         check_value = trim($('user_cell_phone_number').value);
         check_value = check_value.replace(/\s/gi,"");

         check_pass = false;
         
         switch(check_value.substring(0,1))
            {
                case "0":
                    if (check_value.match(/^08[2347][\d+]{7}/)
                        || check_value.match(/^07[1234689][\d+]{7}/)
                        )
                        {
                         check_pass = true;
                        }
                        else
                        {
                         errmsg += "Mobile number provided is incorrect, please correct";
                        }
                    break;
                    
                case "+":
                    if (check_value.match(/^\+27[8][2347][\d+]{7}/)
                        || check_value.match(/^\+27[7][1234689][\d+]{7}/) )
                        {
                            check_pass = true;
                        }
                        else
                        {
                         errmsg += "Mobile number provided is incorrect,please correct";
                        }
                    break;
                
                case "":
                    errmsg += "Please provide a mobile number \n";
                    break;
                
                                    
                default:
                    errmsg += "Mobile numbers have to start with either 08/07 or +27";
                    break;
            }
         
         if (!check_pass)
            {
             //errmsg += "Please provide a valid mobile number";
            }
        }
        
 
    //CHECK THAT THE USERNAME ISN'T ALREADY BEING USED
     if ($('username_exists'))
     {
      check_value = trim($('username_exists').value);
      if (check_value == "true")
      {
       errmsg += "The username chosen is already in use, please choose another \n ";
      
      }//if (check_value == "true")
     }//if ($('username_exists'))
     
 
 if (errmsg.length == 0)
    {
     if ($(form_id))
        {
         $(form_id).submit();
        }
    }
    else
    {
     alert(errmsg);
    }

}//function ValidateCreateUserForm(form_id)
/*************************************************************************** */

function Email_Reset_Password(form_id)
{
 /* function used in ../log_in/index.php after user has tried to log in with a username for 
 3 times and the login button has subsequently been disabled */
 
 var errmsg = "";

 if ($('user_forgot_password_username'))
    {
     var check_value_user = trim($('user_forgot_password_username').value);
     if (check_value_user.length == 0)
        {
        errmsg += "Please provide an username for password reset \n";
        }
    }
 
 
 if ($('user_forgot_password_email'))
    {
    var check_value = trim($('user_forgot_password_email').value);
    if (check_value.length > 0)    
    {
        if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i) )
            {
             errmsg += "Email address provided not a valid email address \nPlease correct the email address \n";
            }
    }
        else
        {
         errmsg += "Please provide an email address to send the new password to \n";
        }
    }
    
    
 if (errmsg.length == 0)
    {
     if ($(form_id))
        {
         $(form_id).submit();
        }
    }
    else
    {
     alert(errmsg);
    }

}//function Email_Reset_Password(form_id)
/*************************************************************************** */
function ValidateAddGroup(form_id)
{
 var err_msg = "";
 
 if ($('NewGroupName'))
    {
     check_value = trim($('NewGroupName').value);
     if (check_value.length == 0)
     {
      err_msg += "Please provide a Group Name";
     
     }
    }
 
 if (err_msg == "")
    {
      if ($(form_id))
        {
         $(form_id).submit();
        }
    
    }
    else
        {
         alert(err_msg);
        }



}//function ValidateAddGroup()
/*************************************************************************** */

function GroupAddContact(school_ref,group_ref)
{
    //alert(school_ref + "::" + group_ref);
    window.location.href = "../logged_in/new_contact.php?selected_school=" + school_ref + "&selected_group=" + group_ref;

}//function GroupAddContact(school_ref,group_ref)
/*************************************************************************** */

function ShowGroupDetails(school_ref,group_ref,AR_USerNo,AccountNo,UserNo,GroupName, update_control)
{
    
    //alert(school_ref + "::" + group_ref + "::" + AR_USerNo + "::" + AccountNo + "::" + UserNo + "::" + update_control);
    var _url = "../_process/_process_GetGroupDetails.php";
    var _postBody = {'AR_UserNo':AR_USerNo, 'AccountNo':AccountNo, 
                        'UserNo':UserNo, 'SchoolRef':school_ref, 'GroupRef':group_ref , 'GroupName':GroupName };    
    
    
    if($(update_control))
    {
        $(update_control).setHTML("<span class=\"infomsg\">Loading " + GroupName + " details ...");
        
        var myAjax = new Ajax(_url,{
                                    method:'post',
                                    postBody:_postBody, 
                                    onSuccess: function ()
                                                {
                                                 if ($(update_control))
                                                    {
                                                     $(update_control).setHTML(this.response.text);
                                                    }
                                                
                                                }
                                    }).request();
    }
    
    
    
}//function ShowGroupDetails()
/*************************************************************************** */
function GroupListRedirect(school_ref,group_ref,AR_UserNo,AccountNo,UserNo,GroupName, update_control)
{
 var _url = "../logged_in/list_groups.php?";
 
 _url += "SchoolRef=" + school_ref;
 _url += "&GroupRef=" + group_ref;
 _url += "&AR_UserNo=" + AR_UserNo;
 _url += "&AccountNo=" + AccountNo;
 _url += "&GroupName=" + GroupName;
 _url += "&UserNo=" + UserNo;

 //alert(_url);
 
 window.location.href = _url; 

}//function GroupListRedirect(school_ref,group_ref,AR_UserNo,AccountNo,UserNo, update_control)

/*************************************************************************** */
function GoTo_UserList(user_no)
{

 if (user_no > 0)
    {
     window.location.href = "../admin/list_users.php?user_no=" + user_no;
    }
}//function GoTo_UserList(user_no)
/*************************************************************************** */
function GoTo_AddGroup()
{

    window.location.href = "../logged_in/new_group.php";

}//function GoTo_AddGroup()

/*************************************************************************** */
function Edit_Group(SchoolRef,GroupRef,GroupName,update_control)
{
    if ($(update_control))
        {
         
         $(update_control).setHTML("<span class='infomsg'>Loading Group Details ...</span>");
         
         var _url = "../_interfaces/_interface_group_edit.php";
         var _postBody = {'SchoolRef':SchoolRef,'GroupRef':GroupRef,'GroupName':GroupName};
         
         var myAjax = new Ajax(_url,
                                {method:'post',
                                postBody:_postBody,
                                update:update_control
                                }
                ).request();
        }

}

/*************************************************************************** */ 
function ConfirmGroupEdit(form_id)
{
  var confirm_edit = confirm("Save details for this Group ?");
  
  if (confirm_edit && $(form_id))
    {
        $(form_id).submit();
    }

}//function ConfirmGroupEdit(form_id)
/*************************************************************************** */ 
function ConfirmGroupDelete(form_id,GroupName)
{
  
  //alert(form_id + "::" + GroupName);
  
  
  if ($(form_id))
    {
        var confirm_delete = confirm("Delete the " + GroupName + " group ? ");
    
        if (confirm_delete)
        {
           $(form_id).submit();
        }//if (confirm_delete)
    
    }//if ($(form_id))
}//function ConfirmGroupDelete(form_id,GroupName)

/*************************************************************************** 
AddKeyListerner : 
Used mainly to create the SmoothScroll on pages wheren if you type a number it runs down the list to the appropiate 
location

IN : id : control on which the keypress event needs to be detected, normally the body's id 
   link_prefix : prefix of the links to the be jumped towards
*/        
    
function AddKeyListerner(id,link_prefix)
{

 $(id).onkeydown = function(event)
     {
        var event = new Event(event);
       
        var key_control = event.control;
        var keypressed_value = event.key;
        
         if (keypressed_value != null 
            && !event.control
            && !event.alt
            && !event.shift
            && (event.target.id.indexOf('ST') == -1 
                && event.target.id.indexOf('st') == -1 
                && event.target.id.indexOf('lt') == -1
                && event.target.id.indexOf('LT') == -1
                )
            
            )
        {
            keypressed_value = keypressed_value.toUpperCase();
            if ($(link_prefix+keypressed_value))
            {
                $(link_prefix+keypressed_value).fireEvent('click');
            }
        }
    }                               
}//function AddKeyListerner(id,link_prefix)
/*************************************************************************** */


//IMPORT PAGE FUNCTIONALITY
function ValidateImport(form_id)
{
  var return_value = false;
  
  var blFile_correct_ext = ValidateFileName('group_file_upload');
  var err_msg = "";
  
  //TEST FOR VALID FILE EXTENTION
  if (!blFile_correct_ext)
    {
     err_msg += "File not a CSV or TXT file \n";
    }

    
  //TEST THAT GROUP HAS BEEN SELECTED
  if ($('selSchoolGroup'))
    {
     var check_value = trim($('selSchoolGroup').value);
     if (check_value == "School")
        {
         err_msg += "Please select a group to import into \n";
        }
    
    }
    
    
  if (err_msg != "")
  {
   alert(err_msg);
   
  }
  else
    {
      if ($(form_id))
      {
       $(form_id).submit();
      }//if ($(form_id))
    }//if (err_msg != "")
    
  return return_value;
}//function ValidateImport(form_id)
/*************************************************************************** */
function ValidateFileName(file_object)
{
    return_value = false;
    
    if ($(file_object))
    {
        filepath = trim($(file_object).value);
    }
    //alert(filepath);
    
    var filename_array = filepath.split("\\");
    file_name = filename_array[filename_array.length-1];
    //alert(file_name);
    
    var file_name_break_up = file_name.split(".");
    file_ext=file_name_break_up[file_name_break_up.length-1];
    
    switch(file_ext)
    {
        case "txt":
        case "csv":
            return_value = true;
            break;
            
        default:
            return_value = false;
        break;
    }

    return return_value; 
}//function ValidateFileName(file_object)

/*************************************************************************** */
function CreateContact(form_id)
{
  //alert(form_id);

 var errmsg = "";

 //alert("Testing");
 
 //CHECK THAT FIRST NAME NOT BLANK
 if ($('contact_firstname'))
    {
     check_value = trim($('contact_firstname').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Firstname for the contact \n";
     }
    
    }
 
 //CHECK THAT LASTNAME NOT BLANK
 if ($('contact_surname'))
    {
     check_value = trim($('contact_surname').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Surname for the contact \n";
     }
    
    }

 //CHECK THAT LANGUAGE HAS BEEN SELECTED
 if ($('contact_language'))
    {
     check_value = trim($('contact_language').value)
     if (check_value == 0)
     {
      errmsg += "Please select a Language for the contact \n";
     }//if (check_value == 0)
    }//if ($('contact_language'))

    //CHECK THAT THE EMAIL ADDRESS IS VALID
    if ($('contact_email'))
        {
            check_value = trim($('contact_email').value);
            if (check_value.length > 0)
            {
                if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
                ||  check_value.indexOf("@") == -1
                ||  check_value.indexOf("..") != -1
                ||  check_value.length == 0
                )
                {
                 errmsg += "Please provide a valid email address for the contact \n";
                }
            }
        }
        
    //CHECK FOR MOBILE NUMBER ( CELL NUMBER ) AND THEN CHECK ACCORDING TO DATABASE CONTRAINTS
    if ($('contact_cellphone'))
        {
         check_value = trim($('contact_cellphone').value);
         check_value = check_value.replace(/\s/gi,"");

         check_pass = false;
         if (check_value.length > 0)
         {
             switch(check_value.substring(0,1))
                {
                    case "0":
                        if (check_value.match(/^08[2347][\d+]{7}/)
                            || check_value.match(/^07[1234689][\d+]{7}/)
                            )
                            {
                             check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect, please correct \n";
                            }
                        break;
                        
                    case "+":
                        if (check_value.match(/^\+27[8][2347][\d+]{7}/)
                            || check_value.match(/^\+27[7][1234689][\d+]{7}/) )
                            {
                                check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect,please correct \n";
                            }
                        break;
                    
                    case "":
                        errmsg += "Please provide a mobile number \n";
                        break;
                    
                                        
                    default:
                        errmsg += "Mobile numbers have to start with either 08/07 or +27 \n";
                        break;
                }
             
             if (!check_pass)
                {
                 //errmsg += "Please provide a valid mobile number";
                }
         }
        }
   
   var check_email = trim($('contact_email').value);
   var check_mobile = trim($('contact_cellphone').value);
   
   if (check_email.length == 0 
       && check_mobile.length == 0)
       {
         errmsg += "Please provide either an email address or mobile number for the contact \n";
       }
   
        
   var groups = $ES('input[type=checkbox]');
   
   //$A : mootools array class
   var group_selected = false;
   $A(groups).each( function(item)
                        {
                        if (item.checked)
                            {
                              group_selected = true;
                            }
                        }
                    );
                    
  if (!group_selected)  
    {
     errmsg += "Please select a group to create the contact into \n ";
    }
  
  
  //CHECK THAT GROUP WAS SELECT
  
  if (errmsg.length == 0)
  {
      if ($(form_id))
        {
         $(form_id).submit();
        }
  }
  else
  {
   alert(errmsg);
  }  
}//function CreateContact(form_id)

/*************************************************************************** */
function EditContact(recipient_no,update_control)
{

  if (!isNaN(recipient_no))
    {
     if ($(update_control))
     {
      _url = "../_interfaces/_interface_contact_edit.php";
      
      cn_name = $('recipient_name_' + recipient_no).value;
      cn_surname = $('recipient_surname_' + recipient_no).value;
      cn_mobile =  $('recipient_mobile_' + recipient_no).value;
      cn_email = $('recipient_email_' + recipient_no).value;
           
     var _postBody = {'contact_recipient_no':recipient_no, 'contact_name': cn_name,'contact_surname': cn_surname,'contact_mobile':cn_mobile,'contact_email':cn_email };
        
     $(update_control).setHTML("Loading contact information...");
     var myAjax = new Ajax(_url,
                            {method:'post',
                            postBody:_postBody,
                            update: update_control,
                            evalScripts:true
                            }
            ).request();
         
     }
    }
}//function EditContact(recipient_no)

/*************************************************************************** */
function DeleteGroupContact(SchoolRef,GroupRef,RecipientNo,GroupName)
{

  //alert(SchoolRef + " : " + GroupRef + " : " + RecipientNo);
  window.location="../_process/_process_DeleteGroupRecipient.php?SchoolRef="+SchoolRef+"&GroupRef="+GroupRef+"&RecipientNo="+RecipientNo+"&GroupName="+GroupName;

}//function DeleteGroupContact(SchoolRef,GroupRef,RecipientNo)
/*************************************************************************** */

function ConfirmContactEdit(form_id)
{
    var errmsg = "";
    
    //err_msg = ValidateContact_Edit();
 //CHECK THAT FIRST NAME NOT BLANK
 if ($('contact_name'))
    {
     check_value = trim($('contact_name').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Firstname for the contact \n";
     }
    
    }
 
 //CHECK THAT LASTNAME NOT BLANK
 if ($('contact_surname'))
    {
     check_value = trim($('contact_surname').value)
     if (check_value.length == 0)
     {
      errmsg += "Please provide a Surname for the contact \n";
     }
    
    }

 //CHECK THAT LANGUAGE HAS BEEN SELECTED
 /*
 if ($('contact_language'))
    {
     check_value = trim($('contact_language').value)
     if (check_value.length == 0)
     {
      errmsg += "Please select a Language for the contact \n";
     }
    
    } 
 */
 
    if ($('contact_email'))
        {
            check_value = trim($('contact_email').value);
            if (check_value.length > 0)
            {
                if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
                ||  check_value.indexOf("@") == -1
                ||  check_value.indexOf("..") != -1
                ||  check_value.length == 0
                )
                {
                 errmsg += "Please provide a valid email address for the contact \n";
                }
            }
        }
        
    //CHECK FOR MOBILE NUMBER ( CELL NUMBER ) AND THEN CHECK ACCORDING TO DATABASE CONTRAINTS
    if ($('contact_mobile'))
        {
         check_value = trim($('contact_mobile').value);
         check_value = check_value.replace(/\s/gi,"");

         check_pass = false;
         if (check_value.length > 0)
         {
             switch(check_value.substring(0,1))
                {
                    case "0":
                        if (check_value.match(/^08[2347][\d+]{7}/)
                            || check_value.match(/^07[1234689][\d+]{7}/)
                            )
                            {
                             check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect, please correct";
                            }
                        break;
                        
                    case "+":
                        if (check_value.match(/^\+27[8][2347][\d+]{7}/)
                            || check_value.match(/^\+27[7][1234689][\d+]{7}/) )
                            {
                                check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect,please correct";
                            }
                        break;
                    
                    case "":
                        errmsg += "Please provide a mobile number \n";
                        break;
                    
                                        
                    default:
                        errmsg += "Mobile numbers have to start with either 08/07 or +27";
                        break;
                }
             
             if (!check_pass)
                {
                 //errmsg += "Please provide a valid mobile number";
                }
         }
        }
    
    var check_email = trim($('contact_email').value);
    var check_mobile = trim($('contact_mobile').value);
    
    if (check_email.length == 0 && check_mobile.length ==0)
    {
     errmsg += "Please provide at least one method of communication \n";
    
    }
    
    if (errmsg.length == 0)
    {
        if ($(form_id))
        {
          $(form_id).submit();
        }
    }
    else
    {
     alert(errmsg);
    }

}//function ConfirmContactEdit()
/*************************************************************************** */

function DeactivateRecipient(recipient_no)
{

  cn_name = $('recipient_name_' + recipient_no).value;
  cn_surname = $('recipient_surname_' + recipient_no).value;
  cn_mobile =  $('recipient_mobile_' + recipient_no).value;
  cn_email = $('recipient_email_' + recipient_no).value;

  window.location.href = "../_process/_process_DeactivateRecipient.php?contact_recipient_no=" + recipient_no 
                        + "&contact_name=" + cn_name 
                        + "&contact_surname=" + cn_surname 
                        + "&contact_mobile=" +  cn_mobile
                        + "&contact_email=" + cn_email ;
      
    /*
    if ($('frmContact_'+recipient_no))
    
        {
            $('frmContact_'+recipient_no).action = "../_process/_process_DeactivateRecipient.php";
            $('frmContact_'+recipient_no).submit();
        
        }
    window.location.href = "../_process/_process_DeactivateRecipient.php?recipient_no=" + recipient_no;
  */
    
}//function DeactivateRecipient(recipient_no)
/*************************************************************************** */

function ReactivateRecipient(recipient_no)
{

  cn_name = $('recipient_name_' + recipient_no).value;
  cn_surname = $('recipient_surname_' + recipient_no).value;
  cn_mobile =  $('recipient_mobile_' + recipient_no).value;
  cn_email = $('recipient_email_' + recipient_no).value;

  window.location.href = "../_process/_process_ReactivateRecipient.php?contact_recipient_no=" + recipient_no 
                        + "&contact_name=" + cn_name 
                        + "&contact_surname=" + cn_surname 
                        + "&contact_mobile=" +  cn_mobile
                        + "&contact_email=" + cn_email ;    
    
    /*
    alert($('frmContact_'+recipient_no));
    if ($('frmContact_'+recipient_no))
        {
            $('frmContact_'+recipient_no).action = "../_process/_process_ReactivateRecipient.php";
            $('frmContact_'+recipient_no).submit();
        
        }
    window.location.href = "../_process/_process_ReactivateRecipient.php?recipient_no=" + recipient_no;
    */
}//function ReactivateRecipient(recipient_no)

/*************************************************************************** */

function AddAdHocContact(update_control)
{

    //alert(update_control);
    var errmsg = "";
    var check_name = "";
    var check_mobile = "";
    var check_email = "";
    
    if ($('ad_hoc_name'))    
        {        
        //VALIDATE NAME TO HAVE NAME AND SURNAME
        var check_name = "";
        check_name = trim($('ad_hoc_name').value);
        
        //CHECK THAT THE NAME FIELD HAVE BEEN FILLED IN
        if (check_name.length > 0)
            {
                
            }
            else
            {
              errmsg += "Please fill in a name to add \n";
            }

        }
        else
        {
         errmsg += "No name available please contact the system administrator \n";
        }
   
    
    //CHECK MOBILE NUMBER
    if ($('ad_hoc_mobile'))
        {
         check_mobile = trim($('ad_hoc_mobile').value);
         check_mobile = check_mobile.replace(/\s/gi,"");

         check_pass = false;
         if (check_mobile.length > 0)
         {
             switch(check_mobile.substring(0,1))
                {
                    case "0":
                        if (check_mobile.match(/^08[2347][\d+]{7}/)
                            || check_mobile.match(/^07[1234689][\d+]{7}/)
                            )
                            {
                             check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect, please correct";
                            }
                        break;
                        
                    case "+":
                        if (check_mobile.match(/^\+27[8][2347][\d+]{7}/)
                            || check_mobile.match(/^\+27[7][1234689][\d+]{7}/) )
                            {
                                check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect,please correct";
                            }
                        break;
                    
                    case "":
                        errmsg += "Please provide a mobile number \n";
                        break;
                    
                                        
                    default:
                        errmsg += "Mobile numbers have to start with either 08/07 or +27";
                        break;
                }
             
             if (!check_pass)
                {
                 //errmsg += "Please provide a valid mobile number";
                }
         }
        }

    if ($('ad_hoc_email'))
        {
            check_email = trim($('ad_hoc_email').value);
            if (check_email.length > 0)
            {
                if (!check_email.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
                ||  check_email.indexOf("@") == -1
                ||  check_email.indexOf("..") != -1
                ||  check_email.length == 0
                )
                {
                 errmsg += "Please provide a valid email address for the contact \n";
                }
            }
            else
            {
             errmsg += "Please provide an email address to add this contact";
            
            }
        }
        
    if (errmsg.length > 0)
        {
         alert(errmsg);
        }
        else
        {
            if ($(update_control))                    
            {
             var child_count = $(update_control).getChildren().length+1;
             var child_count_list_item_id = "Ad_Hoc_Item_" + child_count;
             var child_count_checkbox_item = "chk_Recipient_AdHoc_" + child_count;
             
             
             var remove_button = new Element('input',{'type':'image','src':'../_icons/cross.png','border':'0',
                                                    'events':{'click': function () 
                                                                    {RemoveAdHocRecipient(child_count)}
                                                    }
                                                    });
             /*
             var li_html = check_name + " <input type=\"button\" value=\" - \" class=\"frmbutton\" onclick=\"RemoveAdHocRecipient('" + child_count + "')\" />";
             */
             
             var check_value = check_mobile + check_email;
             
             var child_count_hidden_name_id = "Ad_Hoc_Item_Name_" + child_count;
             var child_count_hidden_name = new Element('input',{'type':'hidden','id':child_count_hidden_name_id,'value':$('ad_hoc_name').value,'name':child_count_hidden_name_id});
             
             var ad_hoc_check_box = new Element('input',{'type':'checkbox','id':child_count_checkbox_item,'value':check_value,'name':child_count_checkbox_item});
             
             
             var new_list_item = new Element('li',{'id':child_count_list_item_id});
             
             //INSERT THE CHECKBOX INTO THE LIST ITEM
             ad_hoc_check_box.injectInside(new_list_item);
             
             //CHECK THE CHECKBOX
              ad_hoc_check_box.checked = true;
             
             //ADD THE TEXT NAME TO THE LIST ITEM
             new_list_item.appendText($('ad_hoc_name').value);
             
             //ADD THE REMOVE X BUTTON TO THE LIST ITEM
             remove_button.injectInside(new_list_item);
             
             //ADD THE HIDDEN NAME VARIABLE
             child_count_hidden_name.injectInside(new_list_item);
             
             //INSERT THE LIST ITEM INTO THE ADHOC LIST
             new_list_item.injectInside(update_control);
             
             if ($('left_block'))
             {
                var elements = $('left_block').getElements("input[type=checkbox]");
                var element_count = elements.length;
                var new_div_height = parseInt(180) + parseInt(element_count*20);
                $('left_block').setStyle('height',new_div_height + 'px');
                
                //$main_div_height = $('Recipient_list').getStyle('height');
                
                
                if ($('Recipient_list').getStyle('height').toInt() < new_div_height)
                {
                  $('Recipient_list').setStyle('height',new_div_height + 'px');
                }//if ($('Recipient_list').getStyle('height') < new_div_height)
             
             
             }
             
            }
        
        }
   CheckStagesDone();
}//function AddAdHocContact(update_control)
/*************************************************************************** */

function RemoveAdHocRecipient(id_no)
{
    //alert("Ad_Hoc_Item_" + id_no);
    //alert($("Ad_Hoc_Item_" + id_no));
    
    if ($("Ad_Hoc_Item_" + id_no))
        {
            $("Ad_Hoc_Item_" + id_no).remove();
        }
    CheckStagesDone();        
    
}//function RemoveAdHocRecipient(id_no)
/*************************************************************************** */

function GroupRecipientSelect(SchoolRef,GroupRef)
{
    //alert(SchoolRef + "_" + GroupRef);
    //alert($("" + SchoolRef + '_' + GroupRef + '_' + 'RecipientList'));
    
    if ($("" + SchoolRef + '_' + GroupRef + '_' + 'RecipientList'))
    {
    
     var children_checkboxed = $("" + SchoolRef + '_' + GroupRef + '_' + 'RecipientList').getElements('input[type=checkbox]');
     //alert(children_checkboxed.length);
     
     $A(children_checkboxed).each(function (item) 
                                   {
                                    //alert(item);
                                    item.checked = $(SchoolRef + '_' + GroupRef + '_' + 'GroupCheck').checked;
                                   }
                                 );
     
    }
    
    CheckStagesDone();


}//function GroupRecipientSelect(SchoolRef,GroupRef)
/*************************************************************************** */ 

function CheckStagesDone()
{
    //CHECK IF ANY GROUPS HAVE BEEN SELECTED, OR IF THERE IS A SELECTED ADHOC USER
    /*
    var group_selected_done = false;
    var contacts_selected_done = false;
    var message_selected_done = false;
    */
    
    var groups_checked = $ES('input[id^=check]');
    
    group_selected = false;
    contacts_selected = false;
    message_composed = false;
    
    
    //alert(groups_checked.length);
    $A(groups_checked).each(function (item)
                                {
                                    if (item.checked)
                                        {
                                         group_selected = true;
                                        }
                                }
                            );
                            
    if (group_selected)
        {
         $('GroupListDone').setHTML("<img src=\"../_icons/accept.png\" border=\"0\" />");
        }
        else
        {
            $('GroupListDone').setHTML("");
        }
    
    
    var contacts_checked = $ES('input[id$=_GroupCheck]');
    
    $A(contacts_checked).each(function (item)
                                {
                                    if (item.checked)
                                        {
                                         contacts_selected = true;
                                        }
                                }
                            );
    
    if (!contacts_selected)                        
    {
        var ad_hoc_contacts = $ES('input[id^=chk_Recipient_AdHoc_]');
        $A(ad_hoc_contacts).each(function (item)
                                    {
                                        if (item.checked)
                                            {
                                             contacts_selected = true;
                                            }
                                    }
                                );
    }
    
    if(contacts_selected) 
        {
         $('RecipientListDone').setHTML("<img src=\"../_icons/accept.png\" border=\"0\" />");
        }
        else
        {
            $('RecipientListDone').setHTML("");
        } 
    
    //CHECK IF EMAIL HAS BEEN SET BODY
    if ($('msg_body'))
        {
        if ($('msg_body').getText().length != 0)
            {
             message_composed = true;
            }
        }
    
    //CHECK IF SMS BODY HAS BEEN SET
    if ($('message'))
    {
     if ($('message').getText().length != 0)
     {
       message_composed = true
     }
    }

    if (message_composed)
    {
     $('MessageDone').setHTML("<img src=\"../_icons/accept.png\" border=\"0\" />");
    }
    else
    {
     $('MessageDone').setHTML("");
    }


}//function CheckStagesDone()
/*************************************************************************** */ 
function CheckMessageStatus()
{
    
    var message_selected_done = false;
      if ($('msg_body'))
        {
        if ($('msg_body').getText().length != 0)
            {
             message_selected_done = true;
            }
        }
    
    
    if ($('message'))
    {
     if ($('message').getText().length != 0)
     {
       message_selected_done = true
     }
    }

    if (message_selected_done)
    {
     $('MessageDone').setHTML("<img src=\"../_icons/accept.png\" border=\"0\" />");
    }
    else
    {
     $('MessageDone').setHTML("");
    }


}//function CheckMessageStatus()


/*************************************************************************** */ 
function LoadGroupContacts(SchoolRef,GroupRef,Type)
{
         
   //alert(SchoolRef + "::" + GroupRef + "::" + Type + "::LoadGroupContact");

    if ($('group_loaded_' + SchoolRef + '_' + GroupRef))
    {
     if ($('group_loaded_' + SchoolRef + '_' + GroupRef).value == "false")
     {
      var item_parentNode = $("" + SchoolRef + "_" + GroupRef + "_Item");
      
      //CREATE THE UL LIST
      
      _url = "../_process/_process_GetSchoolGroup_Type.php";
      _postBody = {'school_ref':SchoolRef,'group_ref':GroupRef,'type':Type};
      
      recipient_list_id = "" + SchoolRef + '_' + GroupRef + '_' + 'RecipientList';
      
      var myAjax = new Ajax(_url,
                            { method:'post',
                             postBody:_postBody,
                             onSuccess: function ()
                                { 
                                    
                                    //alert(this.response.text);
                                    var _data = eval(this.response.text);
                                    ClearInterfaceArea(recipient_list_id);
                                    
                                    //var ul_group_id = "" + SchoolRef + "_" + GroupRef + "_Item_List";
                                    var ul_group_id = "" + SchoolRef + '_' + GroupRef + '_' + 'RecipientList';
                                    var ul_group = $(ul_group_id);
                                    
                                    $A(_data).each(
                                        function(item)
                                            {
                                               //CREATE LIST ITEM FOR RECIPIENT
                                               var li_item_id = 'li_Recipient_' + item.rep_no + '_' + GroupRef;
                                               var li_item = new Element('li',{'id':li_item_id});
                                               
                                               var li_check_box_id = 'chk_Recipient_Group_' + item.rep_no + '_' + GroupRef;
                                               var li_check_box = new Element('input',{'type':'checkbox','id':li_check_box_id,'name':li_check_box_id,'value':item.contact_info});
                                               //alert(item.contact_info);
                                               //LOAD THE CONTACT DETAILS OF THE GROUP RECIPIENT INTO THE CHECKBOX
                                               li_check_box.injectInside(li_item);
                                               
                                               var rep_name = item.firstname + ' ' + item.surname;
                                               
                                               var hidden_name_id = 'Recipient_Group_' + item.rep_no + '_name';
                                               var hidden_name_field = new Element('input',{'type':'hidden','id':hidden_name_id, 'name':hidden_name_id, 'value':rep_name});
                                               
                                               
                                               li_item.appendText(rep_name);
                                               hidden_name_field.injectInside(li_item);
                                               li_item.injectInside(ul_group);
                                               
                                               li_check_box.checked = true;
                                            }//function(item)
                                    )//$A(_data).each(
                                    
                                   var hidden_var_id = "GroupSelectionAltered_" + SchoolRef + "_" + GroupRef;
                                   
                                   var hidden_var = new Element('input',{'type':'hidden','id':hidden_var_id,'value':'true','name':hidden_var_id});
                                   /* 
                                   var li_hidden = new Element('li');
                                   li_hidden.setStyle('display','none');
                                   */
                                   
                                   
                                   hidden_var.injectInside(ul_group.getParent());
                                   //li_hidden.injectInside(ul_group);
                                   
                                   var group_accordion = new Accordion();
                                   
                                   
                                   ul_group.injectInside(item_parentNode) ;
                                   $('group_loaded_' + SchoolRef + '_' + GroupRef).value = "true";
                                        
                                       /* 
                                       var group_recipients = $('Group_Recipients').getElements('input[type=checkbox]');
                                       var div_height = (group_recipients.length * 20) + $('Recipient_list').getStyle('height').toInt();
                                       $('Recipient_list').setStyle('height',div_height + 'px');
                                       */
                                       UpdateDivHeight('Recipient_list','input[type=checkbox]','180');
                                 }
                            }
                           ).request();   
                    ClearInterfaceArea(recipient_list_id);
                    ul_group = $(recipient_list_id);
                    
                    var load_item = new Element('li').setHTML("Loading group contacts");
                    load_item.injectInside(ul_group);
                    
     }
    }

}//function LoadGroupContacts(SchoolRef,GroupRef)

/*************************************************************************** */
function AddRecipientGroup(SchoolRef,GroupRef,update_control,msg_type)
{

    //alert('AddRecipientGroup');

    var GroupName = "";

    if ($('span_' + SchoolRef + '_' + GroupRef))
        {
         var text = $('span_' + SchoolRef + '_' + GroupRef).getText();
         //GroupName = text.substr(0,text.indexOf("["));
         GroupName = text;
        }

if ($('h1_Recipient_list'))
    {


/*        
        <li id="SchoolRef_GroupRef_Item">
            <div id="SchoolRef_GroupRef" class="GroupToggler"><input type="checkbox" id="1_2_GroupCheck" onclick="GroupRecipientSelect('1','2')"> Group Test Name <span id="">[+]</span></div>
              <ul id="1_2_Recipient_List">
                <li><input type="checkbox" id="Testing1" value="email_number" >Hendrik Groenewald</li>
                <li><input type="checkbox" id="Testing2" value="24">Jaco Groenewald</li>
                <li><input type="checkbox" id="Testing3" value="25">Alex Solomons</li>
              </ul>
        </li>        
*/
        
        
       // $('Group_Recipients')
       //CREATE ALL THE ELEMENTS OF THE BLOCK THAT WILL BE INSERTED INTO THE GROUP_RECIPIENTS DIV
       
       if ($('Group_Recipient_List_'+ SchoolRef + "_" + GroupRef ))
        {
               
               //CREATE THE LIST ITEM
               var group_list_id = "" + SchoolRef + "_" + GroupRef + "_Item";
               var group_list_item = new Element('li',{'id':group_list_id});
               
               //CREATE THE CHECKBOX TO BE ADDED TO THE DIV
               var group_list_item_checkbox_id = "" + SchoolRef + "_" + GroupRef + "_GroupCheck";
               var group_list_item_checkbox = new Element('input',{'type':'checkbox','id':group_list_item_checkbox_id,'name':group_list_item_checkbox_id,'value':SchoolRef + '_' + GroupRef,
                                                                    'events': {'click': function () 
                                                                                        {
                                                                                        GroupRecipientSelect(SchoolRef,GroupRef);
                                                                                        } 
                                                                    }          
                                                                    } 
                                                                    
                                                         );
               //CREATE THE HOLDING DIV
               var group_list_item_div_id = "" + SchoolRef + "_" + GroupRef;
               var group_list_item_div_html = "" + GroupName;
               var group_list_item_div = new Element('div',{'id':group_list_item_div_id});
               
               
               var group_name_hidden_id = ""
               if ($('chkGroupName_' + SchoolRef + '_' + GroupRef))
               {
                 chk_value = $('chkGroupName_' + SchoolRef + '_' + GroupRef).value;
                 chk_id='chkGroupName_' + SchoolRef + '_' + GroupRef; 
                 var group_name_hidden = new Element('input',{'type':'hidden','name':chk_id,'id':chk_id, 'value':chk_value});
                 
                 group_name_hidden.injectInside(group_list_item_div);
               }
               
               //ADD THE CHECKBOX TO THE DIV
               group_list_item_checkbox.injectInside(group_list_item_div);
               //group_list_item_checkbox.injectInside('frmMessageSend');
               //ADD THE TEXTNODE TO THE DIV
               group_list_item_div.appendText(group_list_item_div_html);
               
               
               //CREATE THE SELECT CONTACT BUTTON
               var group_list_select_contact_button = new Element('input',{'type':'button','value':'Show contacts','class':'frmbutton',
                                                                    'events': {'click':function()
                                                                                        {
                                                                                        LoadGroupContacts(SchoolRef,GroupRef,msg_type)
                                                                                        }
                                                                               }
                                                                          }
                                                                    );
               //ADD THE BUTTON TO LIST ITEM
               group_list_select_contact_button.injectInside(group_list_item_div);

               var group_name_hidden_id = ""
               if ($('chkGroupName_' + SchoolRef + '_' + GroupRef))
               {
                 chk_value = $('chkGroupName_' + SchoolRef + '_' + GroupRef).value;
                 chk_id='chkGroupName_' + SchoolRef + '_' + GroupRef; 
                 var group_name_hidden = new Element('input',{'type':'hidden','name':chk_id,'id':chk_id, 'value':chk_value});
                 
                 group_name_hidden.injectInside(group_list_item_div);
               }               
               
               
               //ADD THE DIV TO THE LIST ITEM
               group_list_item_div.injectInside(group_list_item);
               
               
                var recipient_list = $('Group_Recipient_List_'+ SchoolRef + "_" + GroupRef).clone();
                recipient_list.id = trim("" + SchoolRef + "_" + GroupRef +"_RecipientList");
                recipient_list.removeClass('hidden_list');
                //alert(recipient_list.id);
                //alert(recipient_list.id);
                
                //ADD THE RECIPIENT LIST TO THE LIST ITEM
                recipient_list.injectInside(group_list_item);
                
                
                //ADD THE LIST ITEM TO THE RECIPIENTS GROUP LIST
                group_list_item.injectInside($('Group_Recipients'));
                                                                         
                $('h1_Recipient_list').setHTML("Recipient List &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "[" + GroupName + " added]");             
                var replace_text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "[" + GroupName + " added]";
                setTimeout("$('h1_Recipient_list').setHTML(\"Recipient List\")",3000);
                
                //CHECK THE CHECKBOX FOR THIS GROUP AND FIRE THE THE ONCLICK EVENT,
                //THIS CHECKS ALL THE RECIPIENTS UNDER THAT LIST
                $(group_list_item_checkbox_id).checked = true;
                $(group_list_item_checkbox_id).fireEvent('click');
                
                //$('Group_Recipients').setStyle('height','500px');
                
        }
        else
        {
        alert("This list doesn\'t exists");
        }
 
        
    }

}//function AddRecipientGroup(SchoolRef,GroupRef)
/*************************************************************************** */  

function RemoveRecipientGroup(SchoolRef,GroupRef)
{
  //alert('RemoveRecipientGroup');
  
  var recipient_div_id = "" + SchoolRef + "_" + GroupRef;
  var GroupName = $(recipient_div_id).getText();
  
  //alert(GroupName);

  var group_list_id = "" + SchoolRef + "_" + GroupRef + "_Item";
  if ($(group_list_id))
    {
     $(group_list_id).remove();
     
     if ($('group_loaded_' + SchoolRef + '_' + GroupRef))
     {
      $('group_loaded_' + SchoolRef + '_' + GroupRef).value = "false";
     }
     
     $('h1_Recipient_list').setHTML("Recipient List &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "[" + GroupName + " removed]");             
     var replace_text = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + "[" + GroupName + " removed]";
     setTimeout("$('h1_Recipient_list').setHTML(\"Recipient List\")",3000);
     
    }
  
}//function RemoveRecipientGroup(SchoolRef,GroupRef)
/*************************************************************************** */  

function ContactSearch(form_id)
{
  if ($(form_id))
    {
     $(form_id).submit();
    }
}//function ContactSearch(form_id)
/*************************************************************************** */ 

function SelectGroup(SchoolRef,GroupRef,update_control,msg_type,checkbox_clicked)
{

  //alert(SchoolRef + "::" + GroupRef + "::" + msg_type);
  
  if (checkbox_clicked != "checkbox_click")
  
  {
      if ($('check_Group_'+ SchoolRef + "_" +GroupRef)
            && !$('check_Group_'+ SchoolRef + "_" +GroupRef).disabled
            )
        {
         $('check_Group_'+ SchoolRef + "_" +GroupRef).checked = !$('check_Group_'+ SchoolRef + "_" +GroupRef).checked;
        }
  }


if ($('check_Group_'+ SchoolRef + "_" +GroupRef)
            && !$('check_Group_'+ SchoolRef + "_" +GroupRef).disabled
            )
        {  
          switch($('check_Group_'+ SchoolRef + "_" +GroupRef).checked)
          {
           case true:
              AddRecipientGroup(SchoolRef,GroupRef,update_control,msg_type);
              if ($('VerifyCreditsRecipients'))
              {
               var newButton = new Element('input',{
                                'type':'button',
                                'class':'frmbutton',
                                'value':'Verify SMS Credits',
                                'events':{'click':function(){VerifySMSCredits('frmMessageSend','VerifyCreditsRecipients')}}
                                
                                });
               
               $('VerifyCreditsRecipients').setHTML("");
               newButton.injectInside($('VerifyCreditsRecipients'));               
              }//if ($('VerifyCreditsRecipients'))
           break;
           
           case false:
              RemoveRecipientGroup(SchoolRef,GroupRef);
              if ($('VerifyCreditsRecipients'))
              {
               var newButton = new Element('input',{
                                'type':'button',
                                'class':'frmbutton',
                                'value':'Verify SMS Credits',
                                'events':{'click':function(){VerifySMSCredits('frmMessageSend','VerifyCreditsRecipients')}}
                                
                                });
               
               $('VerifyCreditsRecipients').setHTML("");
               newButton.injectInside($('VerifyCreditsRecipients'));
              }             
           break;
          }
          
          CheckStagesDone();
          
        };
  
}//function SelectGroup(Group_No)
/*************************************************************************** */ 

function AllRecipientGroupSelect(msg_type)
{
    //alert(msg_type);

    //Function selects/deselects all the groups on the multiple recipient page
    if ($('Select_All'))
    {
      if ($('GroupList'))
        {
         var all_check_box_children = $('GroupList').getElements('input[name^=check_Group_]');
         //alert(all_check_box_children.length);
                  $A(all_check_box_children).each( 
                            function(item)
                            {
                                if (!item.disabled)
                                {
                                    if (item.checked != $('Select_All').checked)
                                    {
                                        item.checked = $('Select_All').checked;
                                        var item_value_array = item.value.split(":");
                                        
                                        var SchoolRef = item_value_array[0];
                                        var GroupRef = item_value_array[1];
                                        
                                        //alert(item.checked);
                                        //SchoolRef,GroupRef,update_control,type,checkbox_clicked
                                        SelectGroup(SchoolRef, GroupRef,'',msg_type,'checkbox_click');
                                    }
                                }
                            });
        }//if ($('GroupList'))
    }//if ($('Select_All'))


}//function AllRecipientGroupSelect()
/*************************************************************************** */ 

function Check_Enter_Pressed_Post_Form(control_id,form_id)
{
 
 $(control_id).onkeydown = function(event)
     {
        var event = new Event(event);
       
        var key_control = event.control;
        var keypressed_value = event.key;
       
        if (keypressed_value == "enter")
        {
          if ($(form_id))
          {
           $(form_id).submit();
          }
        }
            
     }
     

}//function Check_Enter_Pressed()

/*************************************************************************** */ 

function SendContactForm(form_id,update_control_id)
{
    var err_msg = "";

    if ($('contact_name'))
    {
        check_value = trim($('contact_name').value);
    
        if (check_value == "")
        {
            err_msg += "Please provide us with a contact name \n";
        }//if (check_value == "")
    }//if ($('contact_name'))

    if ($('contact_email'))
    {
        check_value = ValidateEmailField('contact_email');
        if (!check_value)
        {
            err_msg += "Please provide us with a contact email address \n";
            
        }//if (!check_value)
    }//if ($('contact_email'))
    
    if (err_msg == "")
    {
        if ($(form_id))
        {
            var_options = "";
            if ($(update_control_id))
            {
                var_options = {update:$(update_control_id)};
            }//if ($(update_control_id))
            
                        
            $(form_id).send(var_options);
            
            if ($(update_control_id))
            {
              $(update_control_id).setHTML("Sending email to InTouch administrator....");
            }//if ($(update_control_id))
            
        }//if ($(form_id))
    }//if (err_msg == "")
        else
        {
         alert(err_msg);
        }//if (err_msg == "")
    
}//function SendContactForm()
/*************************************************************************** */ 

function GoToMessageSend(form_id)
{
  if ($(form_id))
    {
    $(form_id).submit();
    }

}//function GoToMessageSend(form_id)
/*************************************************************************** */ 

function RemoveFile(file_id_no,update_control,attach_control)
{
 //alert(file_id_no);
 if ($('file_remove_span_'+file_id_no))
    {
        $('file_remove_span_'+file_id_no).remove();
    }
    
 if ($('file_'+file_id_no))
    {
        $('file_'+file_id_no).remove();

        if ($('MessageDiv'))
        {
         var msg_div_height = $('MessageDiv').getStyle('height').toInt();   
         msg_div_height = msg_div_height - 20;        
         $('MessageDiv').setStyle('height',msg_div_height);
        }
    }

 if ($(update_control))
    {
     var file_children = $(update_control).getElements('input[type=file]');
     if (file_children.length == 0)
     {
        if ($(attach_control))
        {
            $(attach_control).setText("Attach a file");
        }
        
     }
    }
    
     
}//function RemoveFile(file_id_no)
/*************************************************************************** */ 

function AddFileToEmail(update_control,attach_control)
{
    if ($(update_control))
        {
            var update_control_file_children = $(update_control).getElements('input[type=file]');

            
            var file_element_id = "file_" + update_control_file_children.length;
            var file_element = new Element('input',{'type':'file','id':file_element_id,'name':file_element_id,'class':'frmbox'});
            
            file_element.injectInside(update_control);
            
            //CREATE THE REMOVE LINK HERE ( AS PER GMAIL)
            var remove_span_id = "file_remove_span_" + update_control_file_children.length;
            var remove_span = new Element('span',{'class':'removeFile'
                                    ,'id':remove_span_id 
                                    ,'events':{'click':function () {
                                                            RemoveFile(update_control_file_children.length,update_control,attach_control)
                                                                    }
                                              }
                                    }
                                    ).setText("remove").setStyle('cursor','pointer');
            
            var new_break_line = new Element('br');
            new_break_line.injectInside(remove_span);
            
            remove_span.injectInside(update_control);
            
            if ($('MessageDiv'))
            {
             var msg_div_height = $('MessageDiv').getStyle('height').toInt();   
             msg_div_height = msg_div_height + 20;
             $('MessageDiv').setStyle('height',msg_div_height);
            }
           
           //alert(update_control_file_children.length) ;
           if (update_control_file_children.length == 0)
           {
            $(attach_control).setText("Add another file");
           }
            
            
        }
}//function AddFileToEmail(update_control)
/*************************************************************************** */ 
/* HOME PAGE CODE START */

function LoadHomeSection(load_section, click_control)
{
 if ($('HomeMainArea'))
 {
     var nav_active_item = $$('.Navyellow');
     //nav_active_item.toggleClass('Navgrey');
     $A(nav_active_item).each(
            function (item) 
                {
                    item.removeClass('Navyellow');
                    item.addClass('Navgrey');
                }
            
            )
     
     $(click_control).toggleClass('Navyellow');
     
     if ($(load_section))
     {
      $('HomeMainArea').innerHTML = $(load_section).innerHTML;
     }
 }

}//function LoadHomeSection()
/*************************************************************************** */ 

function UpdateProfileValidate(form_id)
{
    var errmsg = "";
    
    if ($('user_new_password'))
    {   
    
        chk_value_password = trim($('user_new_password').value);
        chk_value_password_confirm = trim($('user_new_password_confirm').value);
    
        if (chk_value_password.length > 0 || chk_value_password_confirm.length > 0)
        {
         if (chk_value_password != chk_value_password_confirm)
         {
          errmsg += "Password and confirmation do not match \nPlease retype password or confirmation \n";
         }
        
        }
    }
   
   //CHECK THE THE EMAIL IS VALID            
   if ($('user_email'))
    {
        check_value = trim($('user_email').value);
        if (check_value.length > 0)
        {
            if (!check_value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
            ||  check_value.indexOf("@") == -1
            ||  check_value.indexOf("..") != -1
            ||  check_value.length == 0
            )
            {
             errmsg += "Please provide a valid email address for the contact \n";
            }
        }
    }
   
   /*
   //CHECK THAT THE MOBILE NUMBER PROVIDED IS VALID 
       if ($('user_mobile'))
        {
         check_value = trim($('user_mobile').value);
         check_value = check_value.replace(/\s/gi,"");

         check_pass = false;
         if (check_value.length > 0)
         {
             switch(check_value.substring(0,1))
                {
                    case "0":
                        if (check_value.match(/^08[2347][\d+]{7}/)
                            || check_value.match(/^07[234689][\d+]{7}/)
                            )
                            {
                             check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect, please correct \n";
                            }
                        break;
                        
                    case "+":
                        if (check_value.match(/^\+27[8][2347][\d+]{7}/)
                            || check_value.match(/^\+27[7][234689][\d+]{7}/) )
                            {
                                check_pass = true;
                            }
                            else
                            {
                             errmsg += "Mobile number provided is incorrect,please correct \n";
                            }
                        break;
                    
                    case "":
                        errmsg += "Please provide a mobile number \n";
                        break;
                    
                                        
                    default:
                        errmsg += "Mobile numbers have to start with either 08/07 or +27 \n";
                        break;
                }
             
             if (!check_pass)
                {
                 //errmsg += "Please provide a valid mobile number";
                }
         }
        }
    
    
    */
    if (errmsg == "")
    {
     //IF THERE IS NO ERROR MESSAGE ( VALIDATION WAS SUCCESSFUL) 
     //AND THE FORM EXISTS SUBMIT THE FORM SO THAT THE USER PROFILE CAN BE UPDATED
     if ($(form_id))
        {
         $(form_id).submit();
        }
    }
        else
        {
         alert(errmsg);
        }
    
}//function UpdateProfileValidate(form_id)
/*************************************************************************** */ 

function UserResetPassword_Confirmation(user_name,user_email)
{
  var answer = confirm("Are you sure you want to reset the password for " + user_name + " ?" );
  
  switch (answer)
  {
   case true:
      window.location = "list_users.php?pw_reset=true&user_name=" + user_name + "&user_email=" + user_email; 
   break;
   
   case false:
   
   break;
  }
  
}//function UserResetPassword_Confirmation()
/*************************************************************************** */ 

function UserStatusChange(user_name,user_email,new_status)
{
    
     var answer = confirm("Are you sure you want to " + new_status.toLowerCase() + " " + user_name + " ?");
     var status = "";
     
     if (answer)
        {
             switch(new_status.toLowerCase())
             {
               case "deactivate":
                 status = "Inactive";
               break;
               
               case "activate":
                 status = "Active";
               break;
             }
             
          window.location = "list_users.php?st_update=true&user_name=" 
                            + user_name 
                            + "&user_email=" + user_email
                            + "&user_status=" + status;
          
        };
  
}//function UserStatusChange(user_name,user_email,new_status)
/*************************************************************************** */ 
function SelectGroupChildren(list_id,check_value)
{
    if ($(list_id))
    {
        checkboxes = $(list_id).getElements('input[type=checkbox]');
        
        
        $A(checkboxes).each(
                    function (item) 
                    {          
                      item.checked = check_value;
                    }//function () 
                    )//each
    }//if ($(list_id))
    

}//function SelectGroupChildren()

/*************************************************************************** */ 
function InTouch_Register(form_id,update_control_id)
{
    var err_msg = "";
    
    if ($('school_name'))
    {
     check_value = trim($('school_name').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with your school\'s name \n";
     }//if (check_value.length == 0)
    }//if ($(''))

    if ($('contact_first_name'))
    {
     check_value = trim($('contact_first_name').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with your first name \n";
     }//if (check_value.length == 0)
    }//if ($(''))

    if ($('contact_surname'))
    {
     check_value = trim($('contact_surname').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with you surname \n";
     }//if (check_value.length == 0)
    }//if ($(''))
    
    if ($('chosen_username'))
    {
     check_value = trim($('chosen_username').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with a chosen username \n";
     }//if (check_value.length == 0)
    }//if ($(''))
   
   password_check = ""; 
    if ($('chosen_password'))
    {
     check_value = trim($('chosen_password').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with a chosen password \n";
     }//if (check_value.length == 0)
     else
     {
      password_check = check_value;
     }
    }//if ($(''))
    
    password_confirm_check = "";
    if ($('chosen_password_confirm'))
    {
     check_value = trim($('chosen_password_confirm').value)
     if (check_value.length == 0)
     {
      err_msg += "Please confirm your password for us again \n";
     }//if (check_value.length == 0)
     else
     {
      password_confirm_check = check_value;
     }
    }//if ($(''))
    
    if (password_confirm_check != password_check)
    {
     err_msg += " Your password and confirmation does not match. Please retype them \n"
    }
    
    
    if ($('contact_mobile'))
    {
     check_value = trim($('contact_mobile').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with a contact number \n";
     }//if (check_value.length == 0)
    }//if ($(''))
    
    if ($('school_contact_number'))
    {
     check_value = trim($('school_contact_number').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with a contact number at the school \n";
     }//if (check_value.length == 0)
    }//if ($(''))
    
    if ($('school_email'))
    {
     check_value = trim($('school_email').value)
     if (check_value.length == 0)
     {
      err_msg += "Please provide us with a contact email address at the school \n";
     }//if (check_value.length == 0)
    }//if ($(''))                            
    
    if ($('chkTC'))
    {
     check_value = $('chkTC').checked;
     if (!check_value)
     {
        err_msg += "To process your request, we require you to accept the Terms and Conditions \n";
     }//if (!check_value)
    
    }//if ($('chkTC'))
    
    
    if ( err_msg == "")
    {
        if ($(form_id))
        {
         var_options = {update:$(update_control_id)};
         $(form_id).send(var_options);
        }//if ($(form_id))
    
    }//if ( err_msg == "")
        else
        {
            alert(err_msg);
        }//if ( err_msg == "")

}//function InTouch_Register(form_id)
/*************************************************************************** */ 
function SendForgotPassword(form_id,update_control_id)
{
    
    
    var err_msg = "";
    
    if ($('username'))
    {
     check_value = trim($('username').value);
     if (check_value.length == 0)
     {
        err_msg += "Please provide us with your username \n";     
     }//if (check_value.length == 0)
    }//if ($('username'))
    
    if (err_msg == "")    
    {
        if ($(form_id))
        {
            var_options = "";
            if ($(update_control_id))
            {
                var_options = {method:'post',update:$(update_control_id)};
            }//if ($(update_control_id))
            //alert("Sending form.. forgot password");
            $(form_id).send(var_options);
            
            if ($(update_control_id))
            {
             $(update_control_id).setHTML("We are processing your request...");
            }
            
        }//if ($(form_id))
    }//if (err_msg == "")
    else
        {
         alert(err_msg);
        }
   return false;
}//function SendForgotPassword(form_id,update_control_id)
/*************************************************************************** */ 
function LoadInterface(interface_name,update_control_id)
{
 
 if (interface_name.indexOf(":") > 0)
 {
    var value_array = interface_name.split(":");
    interface_name = value_array[0];
 }//if (interface_name.indexOf(":") > 0)

 var_url = "";
 
 if ($(update_control_id))
    {
        switch (interface_name.toLowerCase())
        {
            case "forgot_password":
                var_url = "../_interfaces/_interface_forgot_password.php"; 
            break;
            
            case "user_login":
                var_url = "../_interfaces/_interface_user_login.php";
            break;
            
        }//switch (interface_name.toLowerCase())
    
    }//if ($(update_control_id))
    
  if (var_url != "")  
  {
   var myAjax = new Ajax(var_url,{
                            method:'post',
                            update:$(update_control_id),
                            evalScripts:true}
                        ).request();
  }//if (var_url != "") 

}//function LoadInterface(interface_name,update_control_id)
/*************************************************************************** */ 
function CheckLogin(form_id,update_control_id)
{
    var err_msg = "";

    if ($('username'))
    {
     check_value = trim($('username').value);
     if (check_value == "")
     {
      err_msg += "Please provide an username \n";
     }
    }//if ($('username'))

    if ($('password'))
    {
     check_value = trim($('password').value);
     if (check_value == "")
     {
      err_msg += "Please provide a password \n";
     }
    }//if ($('password'))

    
    if (err_msg == "")
    {
        if ($(form_id))
        {
         var_options = "";
         if ($(update_control_id))
         {
            var_options = {method:'post', update:$(update_control_id), evalScripts:true};
         }

         $(form_id).send(var_options);

         if ($(update_control_id))
         {
          $(update_control_id).setHTML("Logging in...");
         }         
         
        }//if ($(form_id))
    }//if (err_msg == "")
        else
        {
         alert(err_msg);
        }//if (err_msg == "")


}//function CheckLogin(form_id,update_control_id)
/*************************************************************************** */ 
function MessageAddChar(char_to_add)
{
    if ($('message'))
    {
        $('message').value += char_to_add;
        $('message').fireEvent('keydown');
    }//if ($('message'))
 
     if ($('msg_body'))
    {
        $('msg_body').value += char_to_add;
        $('msg_body').fireEvent('keydown');
    }//if ($('message'))
 

}//function MessageAddChar(char_to_add)
/*************************************************************************** */ 

function Check_Enter_Press_FireControlEvent(control_id,control_fire_event,event_to_fire)
{
 $(control_id).onkeydown = function(event)
     {
        var event = new Event(event);
       
        var key_control = event.control;
        var keypressed_value = event.key;
       
        if (keypressed_value == "enter")
        {
            
            if ($(control_fire_event))
            {
                $(control_fire_event).fireEvent(event_to_fire);
            }//if ($(control_fire_event))
        }//if (keypressed_value == "enter")
            
     }//$(control_id).onkeydown = function(event)
     

}//function Check_Enter_Pressed()

/*************************************************************************** */
function SetLoginActionOnButton(button_id)
{
    
    $(button_id).addEvent('click', function(){
       CheckLogin('frmLoginMain','login_div');
    });

}//function SetLoginActionOnButton(button_id)
/*************************************************************************** */

function SearchExistingContacts(form_id,update_control_id)
{
    var err_msg = "";
    
    if ($('searchTerm'))
    {
     check_value = trim($('searchTerm').value);
     if (check_value == "")
     {
      err_msg += "Please provide us with search criteria \n";
     }//if (check_value == "")
    
    }//if ($('contact_search'))
    
    if (err_msg == "")
    {
        /*
        if ($(form_id))
        {
            var_options = "";
            if ($(update_control_id))
            {
              var_options = {method:'post',update:$(update_control_id)};
            }
            alert(form_id);
            
            $(form_id).send(var_options);
            
        }//if ($(form_id))
        */
        
        if ($(update_control_id))
        {
            $(update_control_id).setHTML("Searching for existing contacts...");
        
        
         var _url = "../_process/_process_SearchExistingContacts.php";
         var _postBody = {'AR_UserNo':$('AR_UserNo').value,'AccountNo':$('AccountNo').value,
                            'UserNo':$('UserNo').value, 'searchTerm':$('searchTerm').value};
                            
         var newAjax = new Ajax(_url,
                                { postBody:_postBody,
                                  method:'post',
                                  update:$(update_control_id)
                                }).request();
                                
        }//if ($(update_control_id))
        
    }//if (err_msg == "")
        else
        {
         alert(err_msg);
        }//if (err_msg == "")

}//function SearchExistingContacts()
/*************************************************************************** */

function CheckNewUser_Username(username_field_id,update_control_id)
{
    if ($(username_field_id))
    {
        check_username = trim($(username_field_id).value);
        _url = "../_process/_process_CheckUsername.php";
        _postBody = {'check_username':check_username};
        
        if ($(update_control_id))
        {
            
            $(update_control_id).setHTML("Checking login name availability...");
            
            var myAjax = new Ajax(_url,{
                                        method:'post',
                                        postBody:_postBody, 
                                        update:$(update_control_id)
                                        }).request();
        }//if ($(update_control))
    
    }//if ($(username_field_id))
    
}//function CheckNewUser_Username()
/*************************************************************************** */ 
function LoadContactsBySurname_ContactPage(surname_first_char,update_control_id)
{
    //alert(surname_first_char);
    
    check_value = trim(surname_first_char);
    if (check_value != "")
    {
        if ($(update_control_id))
        {
            _url = "../_process/_process_GetContactsBySurname_contactPage.php";
            _postBody = {'surname_first_char':surname_first_char};
            
            $(update_control_id).setHTML("Loading Contacts [" + surname_first_char + "]");
            
            var newAjax = new Ajax(_url,{method:'post',
                                         postBody:_postBody,
                                         update:$(update_control_id)
                                         /*
                                         onSuccess: function()
                                                    {
                                                     var _data = eval(this.response.text);
                                                     $A(_data).each(
                                                        function(item)
                                                        {
                                                            
                                                        }//function(item)
                                                      )//$A(_data).each
                                                    }//onSuccess: function()
                                         */
                                         }
                                  ).request();
        }//if ($(update_control_id))
    
    }//if (check_value != "")

}//function LoadContactsBySurname(surname_first_char,update_control_id)
/*************************************************************************** */ 
function ClearInterfaceArea(control_id)
{
    if ($(control_id))
    {
     if ($(control_id).value)
     {
        $(control_id).value = "";
     }//if ($(control_id).value)
     
     if($(control_id).innerHTML)
     {
        $(control_id).setHTML("");
     }//if($(control_id).innerHTML)
     
    
    }//if ($(control_id))
    
}//function ClearInterfaceArea()
/*************************************************************************** */ 

function LoadContactsBySurname(surname_first_char,update_control_id)
{

    //alert(surname_first_char);
    
    check_value = trim(surname_first_char);
    if (check_value != "")
    {
        if ($(update_control_id))
        {
            _url = "../_process/_process_GetContactsBySurname.php";
            _postBody = {'surname_first_char':surname_first_char};
            
            $(update_control_id).setHTML("Loading Contacts [" + surname_first_char + "]");
            
            var newAjax = new Ajax(_url,{method:'post',
                     postBody:_postBody,
                     //update:$(update_control_id)
                     
                     onSuccess: function()
                                {
                                 
                                 if (this.response.text != "")
                                 {
                                     //alert(this.response.text);
                                     $(update_control_id).setHTML(this.response.text);
                                     
                                     var _data = eval(this.response.text);
                                     
                                     //CLEAR THE RESULTS ARE
                                     ClearInterfaceArea(update_control_id);
                                     
                                     
                                     //FOR EACH ITEM RETURNED CREATE THE CHECK BOX
                                     $A(_data).each(
                                        function(item,index)
                                        {
                                         
                                         //CREAT THE CHECKBOX
                                        var rep_check_box_id = "chk_Surname_Search_" + item.RecipientNo;
                                        var rep_check_box = new Element('input',
                                                                    {
                                                                        'type':'checkbox',
                                                                        'id':rep_check_box_id,
                                                                        'name':rep_check_box_id,
                                                                        'value':item.RecipientNo
                                                                        ,'events':{'click': function () 
                                                                                    {CheckSurnameRecipient(item.RecipientNo,'ContactsToLink')}
                                                                                    }
                                                                    }
                                                                    );
                                         
                                         var rep_name_span_id = "span_Surname_Search_" + item.RecipientNo;
                                         var rep_name_span_value = item.FirstName + " " + item.Surname;
                                         var rep_name_span = new Element('span',{'id':rep_name_span_id,'name':rep_name_span_id}).setHTML(rep_name_span_value);
                                         rep_name_span.addEvent('click',
                                                function()
                                                {
                                                    $(rep_check_box_id).checked = !$(rep_check_box_id).checked;
                                                    CheckSurnameRecipient(item.RecipientNo,'ContactsToLink');
                                                });
                                         rep_name_span.setStyle('cursor','pointer');
                                         
                                         var rep_search_div_id = "div_Surname_Search_" + item.RecipientNo; 
                                         var rep_search_div = new Element('div',{'id':rep_search_div_id,'class':'contact_surname_div'});
                                         
                                         var break_line = new Element('br');
                                         
                                         /*
                                         rep_check_box.injectInside($(update_control_id));
                                         rep_name_span.injectInside($(update_control_id));
                                         break_line.injectInside($(update_control_id));
                                         */

                                         rep_check_box.injectInside(rep_search_div);
                                         rep_name_span.injectInside(rep_search_div);
                                         break_line.injectInside(rep_search_div);
                                         
                                         rep_search_div.injectInside($(update_control_id));
                                         window['mySlide' + item.RecipientNo] = new Fx.Slide(rep_search_div);
                                         
                                         
                                         
                                         /*
                                         $(update_control_id).injectInside(rep_check_box);
                                         $(update_control_id).injectInside(rep_name_span);
                                         $(update_control_id).injectInside(break_line);
                                         */
                                        

                                    }//function(item)                                    
                                  )//$A(_data).each
                                }
                                else
                                {
                                 $(update_control_id).setHTML("No contacts were found starting with a surname starting with " + surname_first_char);
                                }                                  
                                
                                }//onSuccess: function()
                     
                         }
            ).request();
        }//if ($(update_control_id))
    
    }//if (check_value != "")

    


}//function LoadContactsBySurname(surname_first_char,update_control_id)
/*************************************************************************** */ 
function RemoveRecipientFromContactLinkList(recipient_no)
{

    if ($('div_tolink_' + recipient_no))
    {
       if ($('InformationArea'))
       {
        $('InformationArea').setHTML($("span_toLink_" + recipient_no).innerHTML + " removed from the link list..");
       }
       
       $('div_tolink_' + recipient_no).remove();
    }//if ('div_tolink_' + recipient_no)

    if ($('chk_Surname_Search_'+recipient_no))
    {
        
        $('chk_Surname_Search_'+recipient_no).checked = false;
        //alert($('chk_Surname_Search_'+recipient_no).checked);
    }//if ($('chk_Surname_Search_'+recipient_no))
   
}//function RemoveRecipientFromContactLinkList(recipient_no)

/*************************************************************************** */
function CheckSurnameRecipient(recipient_no,update_control_id)
{

   checkbox_checked = $('chk_Surname_Search_'+recipient_no).checked;

   if(checkbox_checked)
   {
    //CHECK IF THE USER IS ALREADY IN THE CONTACT LIST TO BE LINKED TO THE GROUPS SELECTED, IF NOT, ADD USER
    //alert('Checkbox was checked');
    
    if ($('div_tolink_' + recipient_no))
    {
        //alert("Recipient is already part of the Contact linking list");
    }
        else
        {
         //alert('Recipient_Not_Found : Adding to Div');
         
         //ADD THE NEW RECIPIENT TO THE LIST
         var new_contact_link_div_id = 'div_tolink_' +recipient_no;  
         var new_contact_link_div = new Element('div',
                                        {
                                         'id':new_contact_link_div_id,
                                         'name':new_contact_link_div_id,
                                         'class':'contact_link_div'
                                        });

         var rep_name_span_id = "span_toLink_" + recipient_no;
         var rep_name_span_value = $('span_Surname_Search_'+recipient_no).innerHTML;
         var rep_name_span = new Element('span',{'id':rep_name_span_id,'name':rep_name_span_id}).setHTML(rep_name_span_value);
         
         //rep_name_span.addEvent('click',function(){})
         
         var rep_hidden_rep_no_id = "contact_tolink_" + recipient_no;;
         var rep_hidden_rep_no = new Element('input',
                                            { 'type':'hidden',
                                              'id':rep_hidden_rep_no_id,
                                              'name':rep_hidden_rep_no_id,
                                              'value':recipient_no
                                            }
                                            );
         
         var rep_remove_img = new Element('img',{'src':'../_icons/cancel.png',
                                                  'events':{'click': function () 
                                                                        {RemoveRecipientFromContactLinkList(recipient_no)}
                                                           }
                                                    });
         
         rep_name_span.injectInside(new_contact_link_div);
         rep_hidden_rep_no.injectInside(new_contact_link_div);
         rep_remove_img.injectInside(new_contact_link_div);
         
         var_update_children = $(update_control_id).getChildren();
         if (var_update_children.length % 5 ==0)
         {
          var new_break_link = new Element('p');
          new_break_link.injectInside($(update_control_id));
         }
         
         new_contact_link_div.injectInside($(update_control_id));

           if ($('InformationArea'))
           {
            $('InformationArea').setHTML($("span_toLink_" + recipient_no).innerHTML + " added to link list..");
           }//if ($('InformationArea'))

         
        }
   
   }//if(checkbox_checked)
   else
       {
       //CHECK IF USER IS IN THE LIST, IF SO PLEASE REMOVE THE DIV FROM THE RESULTS SET
            RemoveRecipientFromContactLinkList(recipient_no)
       }//if(checkbox_checked)


  
}//function AddSurnameRecipient(recipient_no,update_control_id)
/*************************************************************************** */ 
function FilterSurnameResults(searchTerm_control_id,items_id_prefix)
{
   var surname_result_set = $$('span[id^=' + items_id_prefix + ']');

   
   if ($(searchTerm_control_id))
   {
       $A(surname_result_set).each(
        function(item)
        {
             check_value = item.innerHTML;
             searchTerm = trim($(searchTerm_control_id).value);
             var re = new RegExp(searchTerm,'gi');
             var match = re.exec(check_value);
             
             if (match == null)
             {
              value_array = item.id.split("_");
              itemRecipientNo = value_array[3];
              window["mySlide"+itemRecipientNo].hide();          

              /*
              var hide_control = new Fx.Slide(item.getParent());
              hide_control.hide();
              */
              
              
              
             }//if (match == null)
        }//function(item)
       )//$A(surname_result_set).each(
   }//if ($(searchTerm_control_id))
     
}//function FilterSurnameResults(searchTerm,items_id_prefix)
/*************************************************************************** */ 
function ClearSurnameFilter(items_id_prefix)
{
  var surname_result_set = $$('span[id^=' + items_id_prefix + ']');
  
  //alert(surname_result_set.length);
  
  
   $A(surname_result_set).each
   (
        function(item)
        {
          value_array = item.id.split("_");
          
          itemRecipientNo = value_array[3];
          
          //alert(window["mySlide"+itemRecipientNo]);
          window["mySlide"+itemRecipientNo].show();
          
          /*
          var show_control =  new Fx.Slide(item.getParent());
          show_control.show();
          */
        }//function(item)
   )//$A(surname_result_set).each
   
   
   

}//function ClearSurnameFilter()
/*************************************************************************** */ 
function ResetControl(control_id,control_default_value)
{
  //alert($(control_id));
  //alert(control_default_value);
  
  if ($(control_id))
  {
    if ($(control_id).value == "")
    {
        $(control_id).value = control_default_value;
        switch(control_id)
        {
         case "surname_search_filter_text":
            ClearSurnameFilter('span_Surname_Search_');
         break;
        }
        
        
    }//if ($(control_id).value)
    else
    {    
        if ($(control_id).innerHTML == "")
        {
                $(control_id).setHTML(control_default_value);
        }//if ($(control_id).innerHTML)
    }      
  }//if ($(control_id)

}//function ResetControl(control_id,control_default_value)
/*************************************************************************** */ 
function VerifyLinkContacts(form_id)
{
 var err_msg = "";

 
 //CHECK THAT THERE ARE RECIPIENTS SELECTED TO LINK
 if ($('ContactsToLink'))
 {
    recipient_count = $('ContactsToLink').getChildren().length;
    if (recipient_count == 0)
    {
        err_msg = "No recipients have been selected to be linked \n";
    }//if (recipient_count == 0)
 
 }//if ($('ContactsToLink'))
 

 //CHECK THAT A GROUP HAS BEEN SELECTED TO LINK THE RECIPIENTS TO
 var group_checked = false;
 var groups = $$('input[name^=chk_Group]');
 $A(groups).each(
        function(item)
        {
            if (item.checked)
            {
             group_checked = true;
            }
        }//function(item)
 );
 if (!group_checked)
 {
    err_msg += "No groups have been selected to link recipients to \n";
 }//if (!group_checked)
 
 if (err_msg == "")
 {
    if ($(form_id))
    {
     $(form_id).submit();
    }//if ($(form_id))
 }//if (err_msg == "")
 else
 {
  alert(err_msg);
 }
 
 
}//function VerifyLinkContacts(form_id)
/*************************************************************************** */ 

function AddSystemGroup(SystemGroupDetails,msg_type,UserDetails)
{
  
  var value_array = SystemGroupDetails.split(":");
  //alert(value_array);
  //value_array[0] = System Group Definition [Supporter / LearnerGroup]
  //value_array[1] = SchoolRef  
  //value_array[2] = System Group Sub [ Parents / Grade 1]
  //value_array[3] = Grade Class
  
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];
  
  //alert(GroupDefinition + ":" + SchoolRef + ":" + GroupSub);
  
  if ($('Group_Recipients'))
  {
   var group_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   if (GroupGradeClass != "")
   {
    group_list_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_id += "_Item";
   
   var group_list_item = new Element('li',{'id':group_list_id});
   
   //CREATE THE CHECKBOX TO BE ADDED TO THE DIV
   var group_list_item_checkbox_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   //ADD THE GROUP GRADECLASS INFORMATION, IF IT IS A CLASS THAT HAS BEEN SELECTED
   if (GroupGradeClass != "")
   {
    group_list_item_checkbox_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_item_checkbox_id += "_GroupCheck";
   group_list_item_checkbox_value = GroupDefinition + "_" + SchoolRef + "_" + GroupSub;
   
   var group_list_item_checkbox = new Element('input',{'type':'checkbox','id':group_list_item_checkbox_id,'name':group_list_item_checkbox_id,'value':group_list_item_checkbox_value,'checked':'checked',
                                                        'events': {'click': function () 
                                                                            {
                                                                            SelectGroupChildren(group_list_id,$(group_list_item_checkbox_id).checked);
                                                                            } //function () 
                                                        }//events         
                                                        }//element properties
                                             );
   //CREATE THE HOLDING DIV
   var group_list_item_div_id = SchoolRef + "_" + GroupDefinition + "_" + GroupSub + "_" + GroupGradeClass + "_div";;
   var group_list_item_div_html = GroupDefinition + ":" + GroupSub;
   var group_list_item_div = new Element('div',{'id':group_list_item_div_id});
   
   
   //var group_name_hidden_id = ""
   
   //ADD THE GROUP NAME TO THE LIST ITEM
   chk_value = GroupDefinition + ":" + GroupSub;
   chk_id='chkGroupName_SystemGroup_' + SchoolRef + "_" + GroupDefinition + "_" + GroupSub; 
   var group_name_hidden = new Element('input',{'type':'hidden','name':chk_id,'id':chk_id, 'value':chk_value});
   group_name_hidden.injectInside(group_list_item_div);

   //ADD THE CHECKBOX TO THE DIV
   group_list_item_checkbox.injectInside(group_list_item_div);
   //group_list_item_checkbox.injectInside('frmMessageSend');
   //ADD THE TEXTNODE TO THE DIV
   group_list_item_div.appendText(group_list_item_div_html);
   
   
   //CREATE THE SELECT CONTACT BUTTON
   var group_list_select_contact_button = new Element('input',{'type':'button','value':'Show contacts','class':'frmbutton',
                                                        'events': {'click':function()
                                                                            {
                                                                            LoadSystemGroupContacts(SystemGroupDetails,msg_type,UserDetails);
                                                                            }
                                                                   }
                                                              }
                                                        );
   //ADD THE BUTTON TO LIST ITEM
   group_list_select_contact_button.injectInside(group_list_item_div);

   //ADD THE DIV TO THE LIST ITEM
   group_list_item_div.injectInside(group_list_item);
   
   
    var recipient_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
    if (GroupGradeClass != "")
       {
        recipient_list_id += "_" + GroupGradeClass;
       }//if (GroupGradeClass != "")
    recipient_list_id += "_List"; 
    
    var system_group_recipient_list = new Element('ul',{'id':recipient_list_id,'name':recipient_list_id});
    
    /*
    recipient_list.id = trim("" + SchoolRef + "_" + GroupRef +"_RecipientList");
    recipient_list.removeClass('hidden_list');
    //alert(recipient_list.id);
    //alert(recipient_list.id);
    
    //ADD THE RECIPIENT LIST TO THE LIST ITEM
    recipient_list.injectInside(group_list_item);
    */
    system_group_recipient_list.injectInside(group_list_item);
    
    
    //ADD THE LIST ITEM TO THE RECIPIENTS GROUP LIST
    group_list_item.injectInside($('Group_Recipients'));
    $(group_list_item_checkbox_id).checked = true;

      if ($('VerifyCreditsRecipients'))
      {
       var newButton = new Element('input',{
                        'type':'button',
                        'class':'frmbutton',
                        'value':'Verify SMS Credits',
                        'events':{'click':function(){VerifySMSCredits('frmMessageSend','VerifyCreditsRecipients')}}
                        
                        });
       
       $('VerifyCreditsRecipients').setHTML("");
       newButton.injectInside($('VerifyCreditsRecipients'));
      }

    CheckStagesDone();
  }//if ($('Group_Recipients'))
  
}//function AddSystemGroup()
/*************************************************************************** */ 

function LoadSystemGroupContacts(SystemGroupDetails,msg_type,UserDetails)
{
  var value_array = SystemGroupDetails.split(":");
  
  //value_array[0] = System Group Definition [Supporter / LearnerGroup]
  //value_array[1] = SchoolRef  
  //value_array[2] = System Group Sub [ Parents / Grade 1]
  //value_array[3] = Grade Class
  
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];

  //alert(GroupSub)
  
  var _user_array_values = UserDetails.split(":");
  // _user_array_values[0] = AR_UserNo
  // _user_array_values[1] = AccountNO
  // _user_array_values[2] = UserNo
    
    
    var recipient_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
    if (GroupGradeClass != "")
       {
        recipient_list_id += "_" + GroupGradeClass;
       }//if (GroupGradeClass != "")
    recipient_list_id += "_List";  

    var _postBody = {'AR_UserNo':_user_array_values[0],
                     'AccountNo':_user_array_values[1],
                     'UserNo':_user_array_values[2],
                     'msg_type':msg_type,
                     'SchoolRef':SchoolRef,
                     'SystemGroupType':GroupSub,
                     'ClassRef':GroupGradeClass 
                     };

    var _url = "../_process/_process_GetSchoolSystemGroup_Type.php";
    
    var _newAjax = new Ajax(_url,{
                                method:'post',
                                postBody:_postBody,
                                onSuccess: function ()
                                    {
                                        var __data = eval(this.response.text);
                                        ul_group = $(recipient_list_id);
                                        ClearInterfaceArea(recipient_list_id);
                                        
                                        $A(__data).each( 
                                                function(item)
                                                {
                                                    //alert(item.RecipientNo);
                                                   var li_item_id = 'li_Recipient_' + item.RecipientNo;
                                                   var li_item = new Element('li',{'id':li_item_id});
                                                   
                                                   var li_check_box_id = 'chk_Recipient_SystemGroup_' + item.RecipientNo;
                                                   var li_check_box = new Element('input',{'type':'checkbox','id':li_check_box_id,'name':li_check_box_id,'value':item.ContactInfo});
                                                   //LOAD THE CONTACT DETAILS OF THE GROUP RECIPIENT INTO THE CHECKBOX
                                                   li_check_box.injectInside(li_item);
                                                   
                                                   var rep_name = item.FirstName + ' ' + item.Surname;
                                                   
                                                   var hidden_name_id = 'Recipient_Group_' + item.RecipientNo + '_name';
                                                   var hidden_name_field = new Element('input',{'type':'hidden','id':hidden_name_id, 'name':hidden_name_id, 'value':rep_name});
                                                   
                                                   li_item.appendText(rep_name);
                                                   hidden_name_field.injectInside(li_item);
                                                   li_item.injectInside(ul_group);
                                                   
                                                   li_check_box.checked = true;
                                                
                                                }//function(item)
                                        )//$A(__data).each( 

                                       /*
                                       var group_recipients = $('Group_Recipients').getElements('input[type=checkbox]');
                                       var div_height = (group_recipients.length * 20) + $('Recipient_list').getStyle('height').toInt();
                                       $('Recipient_list').setStyle('height',div_height + 'px');
                                       */
                                       
                                       UpdateDivHeight('Recipient_list','input[type=checkbox]','180');                                                                                
                                    }//onSuccess: function ()
    }).request();
    ClearInterfaceArea(recipient_list_id);
    ul_group = $(recipient_list_id);
    
    var load_item = new Element('li').setHTML("Loading group contacts");
    load_item.injectInside(ul_group);    
 
}//function LoadSystemGroupContacts()
/*************************************************************************** */ 

function LoadSystemLearnerContacts(SystemGroupDetails,msg_type,UserDetails)
{
  
  //alert(SystemGroupDetails + ":" + msg_type + ":" + UserDetails + ":LoadSystemLearnerContacts" );
  var value_array = SystemGroupDetails.split(":");
  
  //value_array[0] = System Group Definition [Supporter / LearnerGroup]
  //value_array[1] = SchoolRef  
  //value_array[2] = System Group Sub [ Parents / Grade 1]
  //value_array[3] = Grade Class
  
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];

  //alert(GroupSub)
  
  var _user_array_values = UserDetails.split(":");
  // _user_array_values[0] = AR_UserNo
  // _user_array_values[1] = AccountNO
  // _user_array_values[2] = UserNo
    
    
    var recipient_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
    if (GroupGradeClass != "")
       {
        recipient_list_id += "_" + GroupGradeClass;
       }//if (GroupGradeClass != "")
    recipient_list_id += "_List";  

    var _postBody = {'AR_UserNo':_user_array_values[0],
                     'AccountNo':_user_array_values[1],
                     'UserNo':_user_array_values[2],
                     'msg_type':msg_type,
                     'SchoolRef':SchoolRef,
                     'ClassRef':GroupGradeClass 
                     };

    var _url = "../_process/_process_GetSchoolLearner_Contacts.php";
    
    var _newAjax = new Ajax(_url,{
                                method:'post',
                                postBody:_postBody,
                                onSuccess: function ()
                                    {
                                        //alert(this.response.text);
                                        
                                        ClearInterfaceArea(recipient_list_id);
                                        var __data = eval(this.response.text);
                                        ul_group = $(recipient_list_id);
                                       
                                        var recipient_count = __data.length;
                                        
                                        $A(__data).each( 
                                                function(item)
                                                {
                                                    //alert(item.RecipientNo);
                                                   var li_item_id = 'li_Recipient_' + item.RecipientNo;
                                                   var li_item = new Element('li',{'id':li_item_id});
                                                   
                                                   var li_check_box_id = 'chk_Recipient_SystemGroup_' + item.RecipientNo;
                                                   var li_check_box = new Element('input',{'type':'checkbox','id':li_check_box_id,'name':li_check_box_id,'value':item.ContactInfo});
                                                   //LOAD THE CONTACT DETAILS OF THE GROUP RECIPIENT INTO THE CHECKBOX
                                                   li_check_box.injectInside(li_item);
                                                   
                                                   var rep_name = item.FirstName + ' ' + item.Surname;
                                                   
                                                   var hidden_name_id = 'Recipient_Group_' + item.RecipientNo + '_name';
                                                   var hidden_name_field = new Element('input',{'type':'hidden','id':hidden_name_id, 'name':hidden_name_id, 'value':rep_name});
                                                   
                                                   li_item.appendText(rep_name);
                                                   hidden_name_field.injectInside(li_item);
                                                   li_item.injectInside(ul_group);
                                                   
                                                   li_check_box.checked = true;
                                                
                                                }//function(item)
                                        )//$A(__data).each( 
                                        
                                        if (recipient_count > 0)
                                        {
                                            var altered_group_field_id = "GroupSelectionAltered_" + recipient_list_id;
                                            var altered_group_field = new Element('input',{
                                                                                        'id':altered_group_field_id,
                                                                                        'name':altered_group_field_id,
                                                                                        'type':'hidden',
                                                                                        'value':'true'});
                                            altered_group_field.injectInside(ul_group);
                                            
                                        }//if (recipient_count > 0)
                                        else
                                        {
                                        
                                        
                                        }////if (recipient_count > 0)
                                       /*
                                       var group_recipients = $('Group_Recipients').getElements('input[type=checkbox]');
                                       var div_height = (recipient_count * 20) + $('Recipient_list').getStyle('height').toInt();
                                       $('Recipient_list').setStyle('height',div_height + 'px');
                                       */
                                       
                                       UpdateDivHeight('Recipient_list','input[type=checkbox]','180');
                                       
                                    }//onSuccess: function ()
    }).request();
    ClearInterfaceArea(recipient_list_id);
    ul_group = $(recipient_list_id);
    
    var load_item = new Element('li').setHTML("Loading group contacts");
    load_item.injectInside(ul_group);
        
}//function LoadSystemLearnerContacts()

/*************************************************************************** */ 
function AddLearnerGroup(SystemGroupDetails,msg_type,UserDetails)
{
  var value_array = SystemGroupDetails.split(":");
  
  //value_array[0] = System Group Definition [Supporter / LearnerGroup]
  //value_array[1] = SchoolRef  
  //value_array[2] = System Group Sub [ Parents / Grade 1]
  //value_array[3] = Grade Class
  //value_array[4] = ClassName
  
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];
  GroupGradeClassName = value_array[4];
  
  //alert(GroupDefinition + ":" + SchoolRef + ":" + GroupSub);
  
  if ($('Group_Recipients'))
  {
   var group_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   if (GroupGradeClass != "")
   {
    group_list_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_id += "_Item";
   
   var group_list_item = new Element('li',{'id':group_list_id});
   
   //CREATE THE CHECKBOX TO BE ADDED TO THE DIV
   var group_list_item_checkbox_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   //ADD THE GROUP GRADECLASS INFORMATION, IF IT IS A CLASS THAT HAS BEEN SELECTED
   if (GroupGradeClass != "")
   {
    group_list_item_checkbox_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_item_checkbox_id += "_GroupCheck";
   //group_list_item_checkbox_value = SystemGroupDetails;
   group_list_item_checkbox_value = GroupDefinition + "_" + SchoolRef +  "_" + GroupGradeClass +  "_" + GroupGradeClassName + "_" + GroupSub;
   
   var group_list_item_checkbox = new Element('input',{'type':'checkbox','id':group_list_item_checkbox_id,'name':group_list_item_checkbox_id,'value':group_list_item_checkbox_value,'checked':'checked',
                                                        'events': {'click': function () 
                                                                            {
                                                                            SelectGroupChildren(group_list_id,$(group_list_item_checkbox_id).checked);
                                                                            } //function () 
                                                        }//events         
                                                        }//element properties
                                             );
   //CREATE THE HOLDING DIV
   var group_list_item_div_id = SchoolRef + "_" + GroupDefinition + "_" + GroupSub + "_" + GroupGradeClass + "_div";;
   var group_list_item_div_html = GroupDefinition + ": Grade " + GroupSub + " : Class : " + GroupGradeClassName;
   var group_list_item_div = new Element('div',{'id':group_list_item_div_id});
   
   
   //var group_name_hidden_id = ""
   
   //ADD THE GROUP NAME TO THE LIST ITEM
   chk_value = GroupDefinition + ":" + GroupSub + ":" + GroupGradeClass + ":" + GroupGradeClassName;
   chk_id='chkGroupName_SystemGroup_' + SchoolRef + "_" + GroupDefinition + "_" + GroupSub + "_" + GroupGradeClass + "_" + GroupGradeClassName; ; 
   var group_name_hidden = new Element('input',{'type':'hidden','name':chk_id,'id':chk_id, 'value':chk_value});
   group_name_hidden.injectInside(group_list_item_div);

   //ADD THE CHECKBOX TO THE DIV
   group_list_item_checkbox.injectInside(group_list_item_div);
   //group_list_item_checkbox.injectInside('frmMessageSend');
   //ADD THE TEXTNODE TO THE DIV
   group_list_item_div.appendText(group_list_item_div_html);
   
   
   //CREATE THE SELECT CONTACT BUTTON
   var group_list_select_contact_button = new Element('input',{'type':'button','value':'Show contacts','class':'frmbutton',
                                                        'events': {'click':function()
                                                                            {
                                                                            LoadSystemLearnerContacts(SystemGroupDetails,msg_type,UserDetails);
                                                                            }
                                                                   }
                                                              }
                                                        );
   //ADD THE BUTTON TO LIST ITEM
   group_list_select_contact_button.injectInside(group_list_item_div);

   //ADD THE DIV TO THE LIST ITEM
   group_list_item_div.injectInside(group_list_item);
   
   
    var recipient_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
    if (GroupGradeClass != "")
       {
        recipient_list_id += "_" + GroupGradeClass;
       }//if (GroupGradeClass != "")
    recipient_list_id += "_List"; 
    
    var system_group_recipient_list = new Element('ul',{'id':recipient_list_id,'name':recipient_list_id});
    
    /*
    recipient_list.id = trim("" + SchoolRef + "_" + GroupRef +"_RecipientList");
    recipient_list.removeClass('hidden_list');
    //alert(recipient_list.id);
    //alert(recipient_list.id);
    
    //ADD THE RECIPIENT LIST TO THE LIST ITEM
    recipient_list.injectInside(group_list_item);
    */
    system_group_recipient_list.injectInside(group_list_item);
    
    //ADD THE LIST ITEM TO THE RECIPIENTS GROUP LIST
    group_list_item.injectInside($('Group_Recipients'));
    $(group_list_item_checkbox_id).checked = true;
    
    
    if ($('VerifyCreditsRecipients'))
      {
       var newButton = new Element('input',{
                        'type':'button',
                        'class':'frmbutton',
                        'value':'Verify SMS Credits',
                        'events':{'click':function(){VerifySMSCredits('frmMessageSend','VerifyCreditsRecipients')}}
                        
                        });
       
       $('VerifyCreditsRecipients').setHTML("");
       newButton.injectInside($('VerifyCreditsRecipients'));
      }
      CheckStagesDone();
    
  }//if ($('Group_Recipients'))
  
}//function AddLearnerGroup()
/*************************************************************************** */ 
function VerifySMSCredits(form_id,update_control_id)
{
    
    if ($(form_id))
    {
        var var_options = "";
        if ($(update_control_id))
        {
            var_options = {'update':update_control_id,'evalScripts':'true'};
            $(update_control_id).setHTML("We are verifying your sms credit balance...");
        }//if ($(update_control_id))
        
        $(form_id).action = "../_process/_process_VerifySMSSend_Credits.php";
        $(form_id).send(var_options);
    
    }//if ($(form_id))

}//function VerifySMSCredits(form_id)
/*************************************************************************** */ 

function SelectSystemGroup(SystemGroupDetails,msg_type,UserDetails,checkbox_clicked)
{
   
   var system_array = SystemGroupDetails.split(":");
   //Supporters:$school_row[0]:Parents','$msg_type','$UserDetails
   //chk_Recipient_Group_System_Supporters_Parents
   var system_group_type = system_array[0];
   system_group_type = system_group_type.toLowerCase();
  
  var checkbox_checked = false;
  
  if (checkbox_clicked != "checkbox_click")
  {
      switch(system_group_type)
      {
       case "learners":
           //Learners:$school_class_info[0]:$school_class_info[1]:$school_class_info[2]:$school_class_info[3]
           //chk_Recipient_Group_System_Learners_Grade_8_1
             if ($('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]))
             {
                $('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]).checked = !$('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]).checked;
                checkbox_checked = $('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]).checked
             }//if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
           
       break;
       
       case "supporters":
       
         if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
         {
            $('chk_Recipient_Group_System_Supporters_' + system_array[2]).checked = !$('chk_Recipient_Group_System_Supporters_' + system_array[2]).checked;
            checkbox_checked  = $('chk_Recipient_Group_System_Supporters_' + system_array[2]).checked;
         }//if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
       break;      
      }//switch(group_type)
  }
  else
  {
      switch(system_group_type)
      {
       case "learners":
           //Learners:$school_class_info[0]:$school_class_info[1]:$school_class_info[2]:$school_class_info[3]
           //chk_Recipient_Group_System_Learners_Grade_8_1
           //chk_Recipient_Group_System_Learners_Grade_8_1
           var name_check = 'chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]; 
             if ($('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]))
             {
               checkbox_checked = $('chk_Recipient_Group_System_Learners_Grade_' + system_array[2] + "_" + system_array[3]).checked
             }//if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
       break;
       
       case "supporters":
       
         if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
         {
           checkbox_checked  = $('chk_Recipient_Group_System_Supporters_' + system_array[2]).checked;
         }//if ($('chk_Recipient_Group_System_Supporters_' + system_array[2]))
       break;      
      }//switch(group_type)
  
  
  }

      switch (checkbox_checked)
      {
        case true:
          switch(system_group_type)
          {
           case "learners":
               AddLearnerGroup(SystemGroupDetails,msg_type,UserDetails);
           break;
           
           case "supporters":
               AddSystemGroup(SystemGroupDetails,msg_type,UserDetails);
           break;      
          }//switch(group_type)
       break;
          
       case false:
          switch(system_group_type)
          {
           case "learners":
              RemoveLearnerGroup(SystemGroupDetails);
           break;
           
           case "supporters":
              RemoveSystemGroup(SystemGroupDetails);
           break;      
          }//switch(group_type)
          
       break;
      }

  if ($('VerifyCreditsRecipients'))
      {
       var newButton = new Element('input',{
                        'type':'button',
                        'class':'frmbutton',
                        'value':'Verify SMS Credits',
                        'events':{'click':function(){VerifySMSCredits('frmMessageSend','VerifyCreditsRecipients')}}
                        
                        });
       
       $('VerifyCreditsRecipients').setHTML("");
       newButton.injectInside($('VerifyCreditsRecipients'));
      
      }

      CheckStagesDone();
  
}//function SelectSystemGroup(Group_No)
/*************************************************************************** */ 
function RemoveLearnerGroup(SystemGroupDetails)
{
  var value_array = SystemGroupDetails.split(":");
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];
  GroupGradeClassName = value_array[4];

   var group_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   if (GroupGradeClass != "")
   {
    group_list_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_id += "_Item";
  
  if ($(group_list_id))
  {
    $(group_list_id).remove();
  }//if ($(group_list_id))

}//function RemoveLearnerGroup(SystemDetails)
/*************************************************************************** */ 
function RemoveSystemGroup(SystemGroupDetails)
{
  var value_array = SystemGroupDetails.split(":");
  
  GroupGradeClass = "";
  
  SchoolRef = value_array[1];
  GroupDefinition = value_array[0];
  GroupSub = value_array[2];
  GroupGradeClass = value_array[3];
  
   var group_list_id = "System_Group_" + SchoolRef + "_" + GroupDefinition + "_" + GroupSub;
   if (GroupGradeClass != "")
   {
    group_list_id += "_" + GroupGradeClass;
   }//if (GroupGradeClass != "")
   group_list_id += "_Item";

  if ($(group_list_id))
  {
   $(group_list_id).remove();
  }//if ($(group_list_id))


}//function RemoveSystemGroup(SystemGroupDetails)
/*************************************************************************** */ 
function UpdateDivHeight(div_id,control_element,extra_offset)
{
    
    var elements = $(div_id).getElements(control_element);
    var element_count = elements.length;
    var new_div_height = parseInt(extra_offset) + parseInt(element_count*20);
    $(div_id).setStyle('height',new_div_height + 'px');

}//function UpdateDivHeight(div_id,control_element)
/*************************************************************************** */ 