/*************************************************************************** 
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 luhn_check(card_number)
{
    var cc_array = new Array();
    cc_array[0] = card_number.substring(0,4);
    cc_array[1] = card_number.substring(4,8);
    cc_array[2] = card_number.substring(8,12);
    cc_array[3] = card_number.substring(12,16);
    
    alert(cc_array[0]);
    alert(cc_array[1]);
    alert(cc_array[2]);
    alert(cc_array[3]);
    
    //cc_array = card_number.split( " " )
    cc_array.reverse()
    digit_string = " ";
    
    for ( counter=0; counter < cc_array.length; counter++ )
    {
        current_digit = parseInt( cc_array[counter] );
        
        if (counter %2 != 0)
        {
            cc_array[counter] *= 2;
        }
        
        digit_string += cc_array[counter];
    
    }
    
    digit_sum = 0;
    
    for ( counter=0; counter<digit_string.length; counter++ )
    {
        current_digit = parseInt( digit_string.charAt(counter) );
        digit_sum += current_digit;
    }
    
    if ( digit_sum % 10 == 0 )
    {
        return true;
    }
    else
    {
        return false;
    }

}
*/

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

 function luhn_check(digits)
 {
   var sum = 0;
   var alt = false;
   var numvar = 0;
   for(var i = digits.length - 1; i >= 0; i--)
   {
     numvar = parseInt(digits.charAt(i));
     if(alt)
     {
       numvar *= 2;
       if(numvar > 9)
       {
         numvar -= 9;
       }
     }
     sum += numvar;
     alt = !alt;
   }
   return sum % 10 == 0;
 }

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

function CheckAddressDetails(supp_no)
{
 var _output = "";
        
      if ($('STAddressStreet'+supp_no))
        {
         if (trim($('STAddressStreet'+supp_no).value) == "")
         {
          _output += "Please provide a street adddress for card delivery purposes \n";
         }
        }

      if ($('STAddressCode'+supp_no))
        {
        var trim_check = trim($('STAddressCode'+supp_no).value);
         //alert("::"+trim_check == ""+"::");
         if (trim_check == ""
            || isNaN(trim_check)
            || trim_check.length != 4
            )
         {
          _output += "Please provide a valid Postal Code [4 digits] \n";
         }
         else
         {
	      if ($('STAddressSuburb1'))        
		{
		   if ($('STAddressSuburb1').length == 0)
		   {
			_output += "The postal code or suburb you have entered, does not exist on our database.  \nPlease contact us on 0860 100 445 and we will promptly assist you.\n";
		   }//if ($('STAddressSuburb1').length == 0)
		}
         
         
         }
        }
        
      /*
      */
      
 
 return _output;
}

/* ************************************************************************** */
function CheckForSupporterSchool(fields)
{


}//function CheckForSupporterSchool(fields)

/* ************************************************************************** */
function CreateDropDown(dropdown_control,value_set)
{

//alert(value_set);
//alert(dropdown_control);

 if ($(dropdown_control)
        && value_set != "")
    {
    var _data = eval(value_set);
    
    $(dropdown_control).length = 0;
    
    
    $A(_data).each(function(item, i) {
       var _option = new Element("option", {'value': item.value}).setText(item.text);
       //alert(item.value);
       $(dropdown_control).adopt(_option);
    });
    

    }

}
/* ************************************************************************** */

function CreateList(list_control,value_set)
{



}
/* ************************************************************************** */

function UpdateClasses(value_control,update_control)
{
    
    if ($(value_control) && $(update_control))
    {
        var url = "../_process/process_search_school_classes.php?schoolref=" + $(value_control).value;
        var myAjax = new Ajax(url, 
                        {
                            method:'POST',
                            onSuccess:function ()
                                {
                                 //alert(this.response.text);
                                 
                                 //alert($(update_control));
                                 //$(update_control).innerHTML = this.response.text;
                                 var classDropdown = new Element('select',{id:'LTClassRef1',name:'LTClassRef1'});
                                 
                                    var _data = eval(this.response.text);
                                    
                                    $A(_data).each(function(item, i) {
                                       var _option = new Element("option", {'value': item.value}).setText(item.text);
                                       //alert(item.value);
                                       classDropdown.adopt(_option);
                                    });
                                 /*
                                 if ($('LTClassRef1'))
                                    {
                                        $('LTClassRef1').remove();
                                    }
                                 */
                                 //alert(classDropdown);
                                 $('LTClassRef1').replaceWith(classDropdown);
                                 
                                }
                        }
                        ).request();
    }
}//function UpdateClasses(value_control,update_control)


/***************************************************************************
CheckNumbers : 
Used to check that the length of the string inputted into the object matches the maxlength allowed,
     if so, jumps to the nextobj

IN : obj : object to check that string length is smaller than maxlength
   : nextobj : object to jump to after maxlength of [obj] has been reached

OUT : The function returns the relevant error message if the telephone number is incorrect, or a blank error.

*/

function CheckNumbers(fieldName,supp_no)
{
/*
    alert($(fieldName+'1_'+supp_no).value);
    alert($(fieldName+'2_'+supp_no).value);
    alert($(fieldName+'3_'+supp_no).value);
*/    
    var errmsg = "";
    
    if (supp_no == "undefined")
        {
         supp_no = 1;   
        }
      
    //alert(supp_no);
    var stNumberProvCode = $(fieldName+'1_'+supp_no).value;
    var stNumberAreaCode = $(fieldName+'2_'+supp_no).value;
    var stNumberHouserCode = $(fieldName+'3_'+supp_no).value;
/*
    alert(stNumberProvCode);
    alert(stNumberAreaCode);
    alert(stNumberHouserCode);
*/
    
    var stNumber = stNumberProvCode + " " + stNumberAreaCode + " " + stNumberHouserCode;
    //alert(stNumber);
    
    if (trim(stNumber) != "")
    {
        if(isNaN(stNumberProvCode + stNumberAreaCode + stNumberHouserCode)
            || stNumber.length !=12)
        {
            switch(fieldName)
            {
             case "STCellno":
                errmsg = "Supporter" + supp_no + "\'s cellphone number is incorrect\n";
             break;
             
             case "STVoiceworkno":
                errmsg = "Supporter" + supp_no + "\'s work number is incorrect\n";
             break;
             
             case "STWorkfaxno":
                errmsg = "Supporter" + supp_no + "\'s work fax number is incorrect\n";
             break;
             
             case "STVoicehomeno":
                errmsg = "Supporter" + supp_no + "\'s home number is incorrect \n";
             break;
                
            }
        }
        
        if (!stNumberProvCode.match(/[0]/))
        {
        switch(fieldName)
            {
             /*
             case "STCellno":
                errmsg = "Supporter" + supp_no + "\'s cellphone number is incorrect\n";
             break;
             */
             
             case "STVoiceworkno":
                errmsg += "Supporter" + supp_no + "\'s work number must start with a 0 \n";
             break;
             
             case "STWorkfaxno":
                errmsg += "Supporter" + supp_no + "\'s work fax must start with a 0 \n";
             break;
             
             case "STVoicehomeno":
                errmsg += "Supporter" + supp_no + "\'s home number must start with a 0 \n";
             break;   
            }            
        }
        
        if (fieldName == "STCellno")
        {
          /*
          if (!stNumberProvCode.match(/[0][87][1234689]/gi))
            {
              errmsg = "Supporter" + supp_no + "\'s cellphone number error, please re enter.\n";
            } 
          */
          switch (stNumberProvCode.substr(0,2))
          {
            case "07":
                if (!stNumberProvCode.match(/[0][7][1234689]/))
                {
                 errmsg += "Supporter" + supp_no + "\'s cell number not in correct format please correct \n";
                }
            break
            
            case "08":
                if (!stNumberProvCode.match(/[0][8][234]/))
                {
                 errmsg += "Supporter" + supp_no + "\'s cell number not in correct format please correct \n";
                }
            break
            
            default:
                errmsg += "Supporter" + supp_no + "\'s cell number has to start with 07 or 08, please correct \n";
            break;

          }
        }
    }
    //alert(errmsg);
    return errmsg;
}//function CheckNumbers()


/***************************************************************************
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)
    
/* ************************************************************************** */
function CheckContactDetails(fields)
{
    var errmsg = "";
    var field_not_filled_id = true;
    
    var fields_array = fields.split("|");
    
    for(i=0; i < fields_array.length ; i++)
        {
         if ($(fields_array[i]))
            {
             if ($(fields_array[i]).value.replace(/\s/gi,"") != "")
                {
                 field_not_filled_id = false;   
                }
            
            }
        
        
        }
    
    if (field_not_filled_id)
        {
         errmsg = "Please provide either a contact number or email address \n";
        }

    return errmsg;
}

    
/***************************************************************************
ValidateSupporterCreate : 
Used to validate the information for a supporterform before the form is submitted

IN : form_id : Id of the form (there can be multiple forms on one page) that contains the supporter create layout
   supp_no : Again, helping in which form elements to validate
*/      

function ValidateSupporterForm(form_id,supp_no)
{

    var errmsg = "";

    if (supp_no == "undefined")
        {
         supp_no = "1";
        }

        
    //alert($(form_id).getElement('input[id=STSurname' + supp_no + ']').value);

    if ($('STSupportingSchoolRef'+supp_no))
    {
     if ($('STSupportingSchoolRef'+supp_no).value == "")
     {
        errmsg += "Please search and select a school for this supporter \n";
     }
    
    }
   
    
    if ($(form_id).getElement('input[id=STSurname' + supp_no + ']').value.replace(/\s/gi,"") != "")
    {  
        
        //TEST THAT TITLE HAS BEEN SELECTED
        if ($('STTitle'+supp_no))
            {
              if ($('STTitle'+supp_no).value=="")
                {
                 errmsg += "Please select an appropiate Title \n";
                }
            }
        
        
        
        //alert($(form_id).getElement('input[id=STSurname' + supp_no + ']').value);
        
        //alert("Before Firstname - Chosenname Check Empty");
        //&&  $(form_id).getElement('input[id=STChosenName' + supp_no + ']').value == ""
        
        if ($(form_id).getElement('input[id=STFirstname' + supp_no + ']').value == "")
                {
                 errmsg += "Please provide a Firstname \n";
                }
        
        //alert("Before Firstname - Chosenname Check Empty");
        /*
        if ($(form_id).getElement('input[id=STFirstname'+ supp_no +']').value.toLowerCase() == $(form_id).getElement('input[id=STChosenName' + supp_no + ']').value.toLowerCase())
        {
            //alert($(form_id).getElement('input[id=STFirstname'+ supp_no +']').value.toLowerCase());
            //alert($(form_id).getElement('input[id=STChosenName' + supp_no + ']').value.toLowerCase());
            errmsg += "Firstname and Chosen name can not be the same \n";
        }
        */
        
        //CHECK FOR ID
        /*
        if ($(form_id).getElement('input[id=STIDNumber' + supp_no + ']').value.replace(/\s/gi,"") != "")
        {
            if ($(form_id).getElement('input[id=STIDNumber' + supp_no + ']').value.match(/[\d+]{13}/)==null)
                {
                 errmsg += "Supporter" + supp_no + " Please provide a valid Identity Number \n";
                }
        }
        */
        if ($(form_id).getElement('input[id=STIDNumber' + supp_no + ']').value.match(/[\d+]{13}/)==null)
            {
             errmsg += "Please provide a valid South African ID number \n";
            };



        
        //CHECK EMAIL ADDY FOR FAULTS
        if ($(form_id).getElement('input[id=STEmailaddress' + supp_no + ']').value != "")
            {
                if (!$(form_id).getElement('input[id=STEmailaddress' + supp_no + ']').value.match(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)
                && stripos(!$(form_id).getElement('input[id=STEmailaddress' + supp_no + ']'),"@") !== 0
                && stripos(!$(form_id).getElement('input[id=STEmailaddress' + supp_no + ']'),"..") === 0
                )
                    {
                        errmsg += "Please provide a valid email address \n ";
                    }
            }
        
        //alert('Before Number checks');
        errmsg += CheckNumbers('STVoiceworkno',supp_no);
        errmsg += CheckNumbers('STWorkfaxno',supp_no);
        errmsg += CheckNumbers('STVoicehomeno',supp_no);
        errmsg += CheckNumbers('STCellno',supp_no);
        
        //CHECK FOR EITHER A NUMBER OR AN EMAIL ADDRESS
        errmsg += CheckContactDetails('STVoiceworkno|STWorkfaxno|STVoicehomeno|STCellno|STEmailaddress1');
        
        
        //errmsg += CheckForSupporterSchool('||||');
        
        if ($('is_village'))
            {
             errmsg += CheckAddressDetails(supp_no);
            }
      
      
      
       //CHECK IF WOOLIES CARD HAS BEEN PUT IN
       //
        if ($('WooliesLunePass') && $('WWcard') )
            {
             check_value = trim($('WWcard').value);
             var bl_valid_lune = false;
             
             //alert(check_value);
             
             //do Luhn validation on the cardnumber provided
             if (check_value.length > 0)
                {
                    //alert("Just before check");
                    bl_valid_lune = luhn_check($('WWcard').value);
                    //alert(bl_valid_lune);
                    
                if (bl_valid_lune)
                    {
                     if ($('WooliesLunePass'))
                     {
                        $('WooliesLunePass').value = "1";
                     }
                    }
                    else
                    {
                     if ($('WooliesLunePass') && $('WWcard'))
                     {
                        $('WooliesLunePass').value = "0";
                        errmsg += "Woolworths card number is invalid. Please check the card number \n";
                     }
                    
                    }//else (bl_valid_lune)
                    
                }//if ($check_value.length > 0)
            

            
            }
      
        
    }
    else  //IF Surname information not found
        {
         errmsg += "To register as a supporter and order a card please provide Surname information \n";
        }
        
    return errmsg;
}//function ValidateSupporterForm(form_id,supp_no)


/***************************************************************************
CheckForJump : 
Used to check that the length of the string inputted into the object matches the maxlength allowed,
     if so, jumps to the nextobj

IN : obj : object to check that string length is smaller than maxlength
   : nextobj : object to jump to after maxlength of [obj] has been reached
*/ 
function CheckForJump(obj,nextobj)
    {
    //alert(obj.name);
    //alert(maxlength + ":" +  obj.value.length);
    var maxlength = $(obj).getProperty('maxlength');
     if (obj.value.length == maxlength)
        {
         $(nextobj).focus();
        }   
    }//function CheckForJump(obj,nextobj)
  
/***************************************************************************
UpdateCode : 
Used to get the postal area code from the dropdown and populate the specified field with the code

IN : value : The selected option's value from the dropdown sent to be analysed
   : obj : object which value is to be set to the value of the postal code
*/    
function UpdateCode(value,obj)
{ //UPDATES THE POSTCODE AREA FROM THE SUBURB DROPDOWNS
  //value = from the dropdown, id = field to update
    
    //alert(value);
    //alert(obj);
        
    varArr = value.split("|");
     if (varArr.length > 0)
     {
       $(obj).value = varArr[0];
     }
 
}//function UpdateCode(value,id)    


/***************************************************************************
ValidateLearnerCreateForm : 
Used to validate the Learner Create form, 
    Checks that ID is just numbers
    Checks that the Chosen name and First name aren't the same
    Checks that either Chosen name and First name are filled in
    Checks that birthdate is in correct format of YYYY-MM-DD
    
IN : form_id : form to check the learnerdetails inside of
   
OUT : Function returns an error message if applicable or a blank error
*/
function ValidateLearnerCreateForm(form_id,lrn_no)
{
    var errmsg = "";    
    
    if ($('LTSchoolRef'+lrn_no))
        {
        if ($('LTSchoolRef'+lrn_no).value=="" 
            || $('LTClassRef'+lrn_no).value =="")
            {
             errmsg += "Please provide school / class information for this learner";
            }
        }
    
    if ($(form_id).getElement('input[id=LTSurname' + lrn_no + ']').value =='')
    {
     errmsg = errmsg + "Surname not provided \n";   
    }    

    
    if ($(form_id).getElement('input[id=LTFirstname' + lrn_no + ']').value == ""
            &&  $(form_id).getElement('input[id=LTChosenname' + lrn_no + ']').value == "")
            {
             errmsg += "Either Firstname or Chosenname needs to be provided \n";
            }
    if ($(form_id).getElement('input[id=LTFirstname' + lrn_no + ']').value == $(form_id).getElement('input[id=LTChosenname' + lrn_no + ']').value)
    {
        errmsg += "First name and Chosen name cannot be the same value \n";
    }
    
    if ($(form_id).getElement('input[id=LTIDNumber' + lrn_no + ']').value.replace(/\s/gi,"") != "")
    {
        if ($(form_id).getElement('input[id=LTIDNumber' + lrn_no + ']').value.match(/[\d+]{13}/)==null)
            {
             errmsg = errmsg + "ID Number not correct, please check again \n";
            }
    }
    
    if ($(form_id).getElement('input[id=LTBirthdate' + lrn_no + ']').value != 'YYYY-MM-DD'
            && $(form_id).getElement('input[id=LTBirthdate' + lrn_no + ']').value.replace(/\s/gi,"") != "")
    {
        if ($(form_id).getElement('input[id=LTBirthdate' + lrn_no + ']').value.match(/[\d+]{4}[-][\d+]{2}[-][\d+]{2}/) == null)
            {
             errmsg = errmsg + "Birtdate not in YYYY-MM-DD format";
            }
    }
 return errmsg;   
}  // function ValidateLearnerCreateForm(form_id) 

/***************************************************************************
GetSupporterLastTrans : 
Used to get the last transaction date of a supporter, if exists.
If no transaction found the page looks to find the last card issued date.
If neither of the above return any values the page returns that there is no
information regarding last card usage or card issue date
    
IN : supp_id : SupporterRef.
   : obj : The control which needs to be updated with the information
   
OUT : Function returns an error message if applicable or a blank error
*/
function GetSupporterLastTrans(supp_id,obj)
{
    //alert(supp_id);
    //alert(obj);

 if (supp_id != "" && $(obj))
    {
        var url = "../_process/process_search_supporter_lasttrans.php?supporterref=" + supp_id;
        $(obj).setHTML("Fetching info...");
        var myAjax = new Ajax(url,{method:'post',update:$(obj)}).request();
    }
    else
    {
     alert("Problem with SupporterRef, please contact administrator");
    }
}//function GetSupporterLastTrans(supp_id,obj)
/***************************************************************************
SearchSupporters : 
Used to search for Supporters on certain criteria
    
IN : supp_id : SupporterRef.
   : obj : The control which needs to be updated with the information
   
OUT : Returns a resultset of all the Supporters found for the criteria given
*/
function SearchSupporters(formID,updateControl)
    {
     // url = "process_search_supporters.php?info_mode=all";
      
      //var mySuppSearch = new Ajax($().action,{ method:'post', update:$('SupporterSearchResults')})
     
     
        //CHECK IF FIELDS HAVE SPACES, IF SO REMOVE THEM
        var varArr = $(formID).getElements('input[type=text]');
        
        if (varArr != null)
        {
         for (i=0;i < varArr.length; i++)
            {
            if (varArr[i].value.replace(/\s/gi, "") == "")
                {
                 varArr[i].value = "";   
                }
            }   
            
        }
     
       $(updateControl).innerHTML = "Searching..." ;
     
      $(formID).send({update:$(updateControl)});
      
    }//function SearchSupporters()


function SearchLearners(formID,updateControl)
{
        var varArr = $(formID).getElements('input[type=text]');
        
        if (varArr != null)
        {
         for (i=0;i < varArr.length; i++)
            {
            if (varArr[i].value.replace(/\s/gi, "") == "")
                {
                 varArr[i].value = "";   
                }
            }   
        }
     
       $(updateControl).innerHTML = "Searching..." ;
       $(formID).send({update:$(updateControl)});

}//function SearchLearners(formID,updateControl)

function FindSuburb(control_id,value)
{
    
    if (value.length >= 3)
    {
        url = "../_process/process_get_possible_suburbs.php";
        url += "?searchterm=" + value.toUpperCase();
        
        if ($(control_id))
            {
             var suburbAjax = new Ajax(url,
                                        {
                                            method:'post',
                                            //update:$(control_id)
                                            onSuccess: function () 
                                            {
                                                //$(control_id).setStyles('position:relative;width:200px');
                                                $(control_id).setHTML(this.response.text);
                                                //alert(this.response.text);
                                            
                                            }
                                        }
                                        ).request();
                                            
            }
    }
    else
        {
         if ($(control_id))
            {
             $(control_id).empty();
            }
        }
    
}//function FindSuburb(control_id,value)

/***************************************************************************
DisplayFamily : 
Used to search for Supporters on certain criteria
    
IN : supp_id : SupporterRef.
   : obj : The control which needs to be updated with the information
   
OUT : Returns a resultset of all the Supporters found for the criteria given
*/
function DisplayFamily(id)
{
 if ($('Family_div_'+id))
    {
        switch($('Family_div_'+id).getStyle('display'))
        {
         case "block":
            $('Family_div_'+id).setStyles({'display':'none'});
            //$('BottomDiv_'+id).setHTML("");
         break;
         
         default:
            if ( $($('LastFamilyDivOpened').value) )
                {
                    $($('LastFamilyDivOpened').value).setStyles({'display':'none'});
                    $($('LastFamilyDivOpened').value).getElement('div[id=BottomDiv]').setHTML("");
                }
                         
            $('Family_div_'+id).setStyles({'display':'block'});
            if ($('Link'+id))
                {
                    $('Link'+id).fireEvent('click');
                }
            $('LastFamilyDivOpened').value = 'Family_div_'+id;
         break;
            
        }

    }

}//function DisplayFamily(id)


 function LoadSupporter(family_id,supp_id)
 {       
   //alert(family_id);
   url = "../_process/display_supporter_update_insert.php?familyref=" +family_id;
   if (supp_id)
   {
    url += "&supporterref=" + supp_id;
   }
   
   if ($('Family_div_'+family_id))
    {
    //$('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("Loading Supporter Information...");            
     var myAjax = new Ajax(url,
                {
                    method:'post',
                    onSuccess: function () 
                                {
                                    //alert(this.response.text);
                                    //alert($('BottomDiv_'+family_id));
                                    //alert($('Family_div_'+family_id).getElement('div[id=BottomDiv]'));
                                    $('Family_div_'+family_id).getElement('div[id=BottomDiv]').setHTML(this.response.text);                     
                                    
                                    //$('SupporterDivTemplate').setHTML(this.response.text);
                                    //$('BottomDiv_'+family_id).setHTML(this.response.text);
                                }
                }
     ).request();
    }       
   
 }//function LoadSupporter(family_id,supp_id)

 function ShowCreateFamilyForm()
 {
   if ($('SupporterSearchResults'))
    {
     $('SupporterSearchResults').setHTML("");
     
     url = "../_process/display_supporter_update_insert.php?CreateFamily=1";
     var MyAjax = new Ajax(url,{method:'post', update:$('SupporterSearchResults')}).request();
     
    }
 }//function ShowCreateFamilyForm() 
 
 
 function SearchSchool(searchTermControl,updatecontrol)
 {
   var url = "../_process/process_search_school.php?schoolsearch=" + $(searchTermControl).value;
   
   if ($(updatecontrol))
    {
        var myAjax = new Ajax(url,{method:'post',update:$(updatecontrol)}).request();
    
    }
 }//function SearchSchool(searchTermControl,updatecontrol)
 
 function SelectSchool(schoolref,updatecontrol,cleancontrol,schoolName)
 {
    if ($(updatecontrol))
        {
         $(updatecontrol).value = schoolref;
        }
    if ($(cleancontrol))
        {
         $(cleancontrol).setHTML("");
        }
    
    for (i=0;i<10;i++)
        { 
         //STSupportingSchool1
         if ($('STSupportingSchool'+i))
            {
                //alert("Insdie"+schoolName);
              $('STSupportingSchool'+i).setHTML(schoolName);
            }
         if ($('STSupportingSchoolRef'+i))
            {
                $('STSupportingSchoolRef'+i).value = schoolref;
            }
        
         //Learner
         if ($('LTSchoolName'+i))
            {
             $('LTSchoolName'+i).setHTML(schoolName);
            }    
         
         if ($('LTSchoolRef'+i))
            {
             $('LTSchoolRef'+i).value = schoolref;
            }
                
        }
    
    UpdateClasses('LTSchoolRef1','LTClassRef1');
    
        
               
 }//function SelectSchool(schoolref,updatecontrol,cleancontrol,schoolName)
 
 
 function SelectRadio(controlID)
 {
 //alert($(controlID));
  if ($(controlID))
  {
     
     if ($('LastCardBatchClicked').value != "")
        {
         //alert($('LastCardBatchClicked').value);
         $($('LastCardBatchClicked').value).getParent().getParent().toggleClass("selectedCardBatch");
        }
     
     
     
     $(controlID).checked = true;
     $('LastCardBatchClicked').value = controlID;
     var daddy =  $(controlID).getParent().getParent().toggleClass("selectedCardBatch");
     //daddy.toggleClass("selectedCardBatch");
    
    
     
  }
 
 }//function SelectRadio(controlID)
 
 function CreateCardBatch(BatchDescriptionControl,updateControl)
 {
  if ($(BatchDescriptionControl) != "" 
        && $(updateControl)
        && $(BatchDescriptionControl).value.replace("/\s/gi","") != ""
        )
    {
     var url = "../_process/process_create_cardbatch.php?card_batch_description=" + $(BatchDescriptionControl).value;
     
     var myAjax = new Ajax(url,{method:'post',update:$(updateControl)}).request();
    
    }
 }//function CreateCardBatch(BatchDescriptionControl,updateControl)
 
 function CloseBatch(CardBatchRef,updateControl)
 {
  if (CardBatchRef != "")
    {
        var url = "../_process/process_close_cardbatch.php?CardBatchRef=" + CardBatchRef;
    
        if ($(updateControl))
            {
             var MyAjax = new Ajax(url,{method:'post',update:$(updateControl)}).request();
            }
            else
            {
             var MyAjax = new Ajax(url,{method:'post'}).request();
            }
    }
 }//function CloseBatch(CardBatchRef,updateControl)
 
 
  function LoadLearner(family_id,learnerRef)
  {
   var url = "../_process/display_learner_update_insert.php?learnerref=" + learnerRef;
   url += "&family_id=" + family_id;
   
   if ($('Family_div_'+family_id))
    {
    $('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("Loading information.. please be patient");
     var myAjax = new Ajax(url,
                    {
                        method:'post',
                        update:$('Family_div_'+family_id).getElement('div[id=BottomDiv]')
                    }
               ).request();
    }
  }//function LoadLearner(family_id,learnerRef)
  
  
/* ************************************************************************** */
 function SaveSupporter(form_id)
 {
  var validateForm = "" + ValidateSupporterForm(form_id,'1');
  
  if ($('IDFound'))
    {
      if ($('IDFound').value == 1)
        {
         validateForm += "A supporter with this ID number already exists on file. \n Please verify that the number is correct or alternatively \n contact the MySchool Client Service Center on 0860 100 445 to resolve the matter \n";
        }
    }
    
  if ($('WooliesCardFound'))
    {
      if ($('WooliesCardFound').value == 1)
        {
         validateForm += "Your woolworthscard was found to be linked to a supporter in our system \nPlease contact customer center at 0860 100 445 \n";
        }
    }
    
if ($('WWcard')) 
    {
     if ($('WWcard').value.length == 16 && !isNaN($('WWcard').value))
        {     
         if ($('WooliesLunePass'))      
         {
          if ($('WooliesLunePass').value != '1')
             {
               validateForm += "The Woolworthscard number you have provided seems to be invalid \nPlease check that the number is filled in correctly \n";
             }
         }
        }
    }
    
if ($('SupportingSchool1'))
    {
     if ($('SupportingSchool1').value == "")
        {
         
         validateForm += "Please select a School that you would like to support, \n";
         validateForm += "by starting to type the name of your desired school in the Name area \n";
        }
    }
                                
  if (validateForm == "")
     {
        $(form_id).submit();
     /*
     
      var url = "../_process/process_supporter.php?supporterRef=" + $('SupporterRef').value;
      
      var CardBatchArray = $ES('input[type=radio]','CardBatchControl');
      var CardBatchSelected = false;
      
      for (i=0;i<CardBatchArray.length;i++)
        {
         if (CardBatchArray[i].checked)
            {
             //alert(CardBatchArray[i].value);
             CardBatchSelected = true;
             url += "&CardBatchRef=" + CardBatchArray[i].value;
            }
         
        }
      
      /*
      if ($('Supp_NewCard1').checked && !CardBatchSelected)
        {
         alert("Please select a CardBatch, or create a new CardBatch, in which to place this card order");
        }
        else
        {
     
          if ($(form_id))
            {
             $(form_id).action = url;
             if ($('new_family'))
                {
                $(form_id).send({update:$('SupporterSearchResults')});
                }
                else
                {
                    //alert($('supp_button'));
                    
                    if ($('supp_button'))
                        {
                         var inputboxes = $ES('input[type=text]','formSupporter');
                         
                         for (i=0;i< inputboxes.length;i++)
                            {
                             inputboxes[i].setProperty('readonly','readonly');
                            }
                        
                        $('supp_button').value = "Sending request.....";
                        
                         $('supp_button').disabled = true;
                        }                    
                    //$(form_id).send({update:$(form_id),evalScripts:true});
                    $(form_id).submit();
                }
            }
        //}
        */
     }
     
     else
     {
      alert(validateForm);
     } 
 }//function SaveSupporter(form_id)
 
/* ************************************************************************** */
function SaveLearner(form_id)
{

    var validateLearner = ValidateLearnerCreateForm(form_id,'1');

    if (validateLearner == "")
    {
    url = "../_process/process_learner.php";

      if ($(form_id))
        {
         //alert(url);
         $(form_id).action = url;
         $(form_id).send({update:$(form_id),evalScripts:true});
         
        }
    }
    else
    {
     alert(validateLearner);
    }
        
}//function SaveLearner(form_id)

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

function RefreshCardBatchDiv()
{
var refreshID = 0;
if (refreshID)
    {
     clearTimeout(refreshID);
    }

 update_control = 'CardBatchList';
 cardbatchref = "";
 
 var rdArray = $ES('input[type=radio]',update_control);
 
 for (i=0;i<rdArray.length;i++)
    {
     if (rdArray[i].checked)
      cardbatchref = rdArray[i].value
    }
 
 var url = "../_process/process_create_cardbatch.php?cardbatchref=" + cardbatchref;
 url += "&refresh=1";
 
 if ($(update_control))
    {
      var myAjax = new Ajax(url,{method:'post',update:$(update_control)}).request();
    }

 refreshID = setTimeout('RefreshCardBatchDiv()',5000);
 //alert(refreshID)  ;
}

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

function PostCodeLookup(postcode,suburbcontrol)
{

    var url="../_process/process_lookupsuburb.php";
    postcode = postcode.replace(/\s/gi,"");
    var _postBody = {'postcode':postcode};
    
    
    if ($(suburbcontrol) && postcode != "" && postcode.length > 3)
        {
        if ($('STAdressSuburbPlaceHolder'))
        {
        
         $img_el = new Element("img",{'src':'../_images/ajax_loading/rotating_arrow.gif','id':'LoadingImage'});
         $img_el.setStyles('width:20px; height:21px');
         
         $span_el = new Element('span', {'id':'LoadingSpan'}).setText("Loading...");
         
         $('STAdressSuburbPlaceHolder').setHTML("");
         
         if ($('ApplicationForm'))
            {
                $('ApplicationForm').setStyle("cursor","wait");
                $('STAddressCode1').setStyle("cursor","wait");
            }
         //$('STAdressSuburbPlaceHolder').adopt($img_el);
         //$('STAdressSuburbPlaceHolder').adopt($span_el);
         
         if ($('STAddressSuburb1'))
            {
             $('STAddressSuburb1').length = 0;
            }
         
        }
         var myAjax = new Ajax(url,
                                {
                                    method:'post',
                                    postBody: _postBody,
                                    onSuccess: function() 
                                    {
                                        /*
                                        if ($('SuburbMatches'))
                                            {
                                             $('SuburbMatches').setHTML(this.response.text);
                                            }
                                        */
                                        
                                        if ($('ApplicationForm'))
                                            {
                                             $('ApplicationForm').setStyle("cursor","default");
                                             $('STAddressCode1').setStyle("cursor","default");
                                            }
                                        
                                        if ($('LoadingImage'))
                                        {
                                         $('LoadingImage').remove();
                                         $('LoadingSpan').remove();
                                        }
                                        var _data = eval(this.response.text);
                                             if ($('STAdressSuburbPlaceHolder'))
                                                {                                        
                                                if ($('STAdressSuburbPlaceHolder'))
                                                    {
                                                     //$('STAddressSuburb1').remove();
                                                     $('STAddressSuburb1').length = 0;
                                                     //var suburbdropdown = new Element("select",{id:'STAddressSuburb1',name:'STAddressSuburb1'});
                                                     
                                                     //$('STAdressSuburbPlaceHolder').injectAfter(suburbdropdown);
                                                    }
                                                }
                                        var _count = -1;
                                        $A(_data).each(function(item,i)
                                            {
                                              var _option = new Element("option", {'value': item.value}).setText(item.text);
                                              $('STAddressSuburb1').adopt(_option);
                                              _count = i;
                                            }
                                        );
                                        if (_count >= 0)
                                        {
                                            $('STAddressSuburb1').setStyle('display','block');
                                        }
                                        else
                                        {
                                         $('STAdressSuburbPlaceHolder').setHTML("<span class='Information'>No suburbs founds for code supplied </span>");
                                         if ($('STAddressCode1'))
                                            {
                                                $('STAddressCode1').focus();
                                                $('STAddressCode1').select()
                                            }
                                         $('STAddressSuburb1').setStyle('display','none');   
                                        }
                                        
                                    }
                                }).request();
        
        
        }
        else
        {
         if (postcode.length==0 || postcode.length <= 3)
         {
          $(suburbcontrol).empty();
          $('STAdressSuburbPlaceHolder').setHTML("Please input Postal Code to receive selection");
          $('STAddressSuburb1').setStyle('display','none');
          if ($('ApplicationForm'))
              {
                $('ApplicationForm').setStyle("cursor","default");
                $('STAddressCode1').setStyle("cursor","default");               
              }
         }
        }
}//function PostCodeLookup(postcode,suburbcontrol)

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

 function UpdateFamilyLearners(family_id)
 {
   //alert(family_id);
   url = "../_process/process_get_family_learners.php?familyref=" + family_id;
   
   if ($('Family_div_'+family_id))
   {
       //alert('Starting Update');
        $('Family_div_'+family_id).getElement('div[id=BottomDiv]').setHTML("");
        $('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("Updating Learners..please be patient");
        var myAjax = new Ajax(
                            url,
                            {
                                method:'post',
                                update:$('Family_div_'+family_id).getElement('div[id=LearnerDiv_Family]'),
                                evalScripts:true,
                                onSuccess : function () 
                                    {
                                     $('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("");   
                                    }
                            }
                            ).request();
   }
 }//function UpdateFamilyLearners(family_id) 

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

function UpdateFamilySupporters(family_id)
{
    url = "../_process/process_get_family_supporters.php?familyref=" + family_id;

    if ($('Family_div_'+family_id))
    {
        $('Family_div_'+family_id).getElement('div[id=BottomDiv]').setHTML("");
        $('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("Updating Supporters..please be patient");
        var myAjax = new Ajax(
                            url,
                            {
                                method:'post',
                                update:$('Family_div_'+family_id).getElement('div[id=SupporterDiv_Family]'),
                                evalScripts:true,
                                onSuccess: function () 
                                    {
                                     $('Family_div_'+family_id).getElement('div[id=Information_Display]').setHTML("");   
                                    }
                            }
                            ).request();     

     
    }
}//function UpdateFamilySupporters(family_id)

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

function ClearPage()
{
 
 if ($('FamilyForm'))
    {
        $('FamilyForm').setHTML("");
    }

 if ($('SupporterSearch'))   
    {
        var SearchTextBoxes = $ES('input[type=text]', 'SupporterSearch');
        
        for (i=0;i < SearchTextBoxes.length ; i++)
        {
         SearchTextBoxes[i].value = "";
        
        }
    }
 
 if ($('SupporterSearchResults'))
    {
     $('SupporterSearchResults').setHTML("");
    }
 /*
 if ($('LastFamilyDivOpened'))
    {
     $('LastFamilyDivOpened').value = "";
    }
 */
}//function ClearPage()

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

function ChooseSuburb(name,value)
{
    //alert(name+"::"+value);
    
    if ($('STAddressCode1'))
        {
         $('STAddressCode1').value = value;
         
         if ($('STAddressSuburb1'))
            {
              $('STAddressSuburb1').empty();
              var _option = new Element('option',{'value':value+"|"+name}).setText(name);
              $('STAddressSuburb1').adopt(_option);
            }
         
        }
}//function ChooseSuburb(name,value)

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

function CheckKeyPress(event,form_id,update_control)
{

        var event = new Event(event);
       
        var key_control = event.control;
        var keypressed_value = event.key;
        if (keypressed_value == "enter")
        {
            switch(form_id)
                {
                 case "SuppSearchForm":
                    SearchSupporters(form_id,update_control);
                 break;
                 
                 case "LearnerSearchForm":
                    SearchLearners(form_id,update_control);
                 break;
                
                }
        }

}//function CheckKeyPress(event,form_id,update_control)

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

function Check_UncheckControl(obj_id)
{

    if ($(obj_id))
        {
         $(obj_id).checked = !$(obj_id).checked;
        }

}//function Check_UncheckControl(obj_id)

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

function ConcatField(fields_from,update_field)
{

    var field_array = fields_from.split('|');
    var interm_value = "";
    
    for(i=0;i < field_array.length; i++)
        {
         if ($(field_array[i]))
            {
                interm_value += $(field_array[i]).value;
            }
        }
    
    if ($(update_field))
        {
         $(update_field).value = interm_value;
        
        }
}//function ConcatField(fields_from,update_field)
/* ************************************************************************** */


function CheckSupporterPAN(PAN,update_obj)
{
    //alert(!isNaN(PAN));
    
    var _url = "../_process/process_supporter_checkPAN.php";
    
    var _postBody = {'suppPAN':PAN};
    
    if (PAN.length == 16 
        && !isNaN(PAN))
    {
      //alert("Inside this");
      var myAjax = new Ajax(
                               _url,
                                {
                                    method:'post',
                                    postBody:_postBody,
                                    onSuccess: function ()
                                        {
                                        //alert(this.response.text);
                                         if ($(update_obj))
                                            {
                                             $(update_obj).setHTML(this.response.text);
                                            }
                                        }
                                }
                            ).request();    
    }
    else
    {
     if ($(update_obj))
        {
         $(update_obj).setHTML("");
        }
    
    }

}

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

function LoadOtherVillages(update_control, school_type)
{
    //alert("testing run");
     var _url = "../_process/school_get_by_type.php";
     var _postBody = {'school_type':school_type};
     
     
     if (!isNaN(school_type) && school_type != "")
     {
              var myAjax = new Ajax(
                                _url,
                                {
                                    method:'POST',
                                    postBody: _postBody,
                                    onSuccess: function ()
                                                {
                                                 CreateDropDown('STSupportingSchoolRef1',this.response.text);
                                                 }
                                                
                                }
                                ).request();
     }

}//function LoadOtherVillages(update_control, school_type)

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

function CheckOtherVillagesSelected(obj)
{
    //alert($(obj).value=='Other');
     if ($(obj).value == 'Other')
        {
          LoadOtherVillages(obj,4);
        }
 }

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

 function FetchSchools(obj,update_control)
 {
 
  var blDoRequest = true;
 
  if ($(update_control))
    {
    
    if ($(update_control).value == "0"
        || $(update_control).value == "10969"
        )
        {
        if ($(obj).value.length != 0)
         blDoRequest = false;
        }
    }
 
  if ($(obj).value.length >= 5 
        && $(update_control)
        && blDoRequest
        )
    {
        var _url = "../_process/process_search_school.php";
        var _postBody = {'schoolsearch':$(obj).value};
        //alert(update_control);
        
       var myAjax = new Ajax(_url,
                        {
                         method:'post',
                         postBody: _postBody,
                         onSuccess: function ()
                            {
                             CreateDropDown(update_control,this.response.text);
                            }
                        }
                        ).request();
    
    }
    else
    {
     if (blDoRequest)
        {
            $(update_control).length = 0;
        }
    
    }

 }

/* ************************************************************************** */
 
 function Check_IDNumber_In_system(obj,return_err)
 {

    if ($(obj).value.length==13 && !isNaN($(obj).value))
        {
           
           var _url = "../_process/process_check_supporter_IDnumber.php";
           var _postBody = {'supp_id_num':$(obj).value};
           
           var myAjax = new Ajax(
                                _url,
                                {
                                    method:'POST',
                                    postBody: _postBody,
                                    onSuccess: function ()
                                        {
                                            var _response = trim(this.response.text);
                                            
                                            if (return_err==1)
                                                {
                                                 return _response;
                                                }
                                                else
                                                {
                                                  if(_response.length > 0 && _response != "")
                                                  {
                                                   alert(_response);
                                                   if ($('IDFound'))
                                                    {
                                                     $('IDFound').value = 1;
                                                    }
                                                  
                                                  }
                                                  else
                                                  {
                                                    if ($('IDFound'))
                                                        {
                                                            $('IDFound').value = 0;
                                                        }
                                                  }
                                                }
                                        
                                        }
                                }
                                ).request();
           }
 }//function Check_IDNumber_In_system(value,return_err)

/* ************************************************************************** */
 
 function Check_WooliesNumber(obj,return_err)
 {
   if ($(obj).value.length==16 && !isNaN($(obj).value))
    {
     var _url = "../_process/process_search_woolworths_cards.php";
     var _postBody = {'cardnumber':$(obj).value};
     
     var myAjax = new Ajax(
                        _url,
                        {
                            method:'POST',
                            postBody: _postBody,
                            onSuccess: function ()
                                {
                                    var _response = trim(this.response.text);
                                    
                                    if (return_err==1)
                                        {
                                         return _response;
                                        }
                                        else
                                        {
                                          if(_response.length > 0 && _response != "\n")
                                          {                         
                                           alert(_response);
                                           if ($('WooliesCardFound'))
                                            {
                                                $('WooliesCardFound').value = 1;
                                            }
                                          }
                                          else
                                          {
                                           if ($('WooliesCardFound'))
                                            {
                                                $('WooliesCardFound').value = 0;
                                            }
                                          }
                                        }
                                
                                }
                        }
                        ).request();
    }
    else
    {
      $('WooliesCardFound').value = 0;
    }
 }

 /******************************************************************* */
 
 function ChangeWoolworthPermissions(positive_negative)
 {
 
     switch(positive_negative)
         {
         case "yes" :
              if ($('STWWPromo1'))
                {
                 $('STWWPromo1').checked = false;
                }
             
              if ($('STWWShare1'))
                {
                 $('STWWShare1').checked = false;
                } 
          break;
          
          case "no":
              if ($('STWWPromo1'))
                {
                 $('STWWPromo1').checked = true;
                }
             
              if ($('STWWShare1'))
                {
                 $('STWWShare1').checked = true;
                } 
          break;          
         }
 
 }//function ChangeWoolworthPermissions()
 /******************************************************************* */ 