/**
 * JobSpeed Website
 * Javascript Validation
 *
 * @author $Author: nick $
 * @copyright 2007 JobSpeed
 * @filesource
 * @link http://www.jobspeed.com.au
 * @package JobSpeed
 * @subpackage JavaScript
 */

/**
 * Validate whether a string is an email address or not
 *
 * @param string str Email address to validate
 * @return boolean Valid email address?
 * @todo Improve this validation. Perhaps use AJAX to check email address against DB
 */
  function isAllValidEmail(str) {
    return (str.indexOf("@") > 0 && str.indexOf(".") > 0); 
  }

  function isValidEmail(str) {
    return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
  }
  
  function isValidPhone(phone) {
    if (isInteger(phone) == false) {
      message = "Error: Invalid contact number, including area code with no spaces";
      return false;
    } else if (phone.length != 10 && phone.length != 6) {
      message = "Error: Invalid contact number, including area code with no spaces";
      return false;
    }
    return true;
  }

//function to check whether integer or not
  function isInteger(num) {
    var bln = true;
    var n;
    var numbers = "0123456789";
    var phoneNumber = trimAll(num);

    for (i = 0; i < phoneNumber.length; i++) {
      n = phoneNumber.charAt(i);
      if (numbers.indexOf(n) == -1) {
        bln = false;
      }
    }
    return bln;
  }

/**
 * Process refer friend form using AJAX
 */
  function postReferFriend(obj) {
    prevAlertBox = 'sendToFriendBox';
    showHideBox('hide', 'sendToFriendBox');
    // open up the loading alert. it has id tempAlert in it which is replaced after AJAX is called
    alert('', '<div id="tempAlert" style="text-align: left;">Sending email...<br/><br/><img style="margin: auto;" src="images/loading.gif" /></div>');
     
    var poststr = getQueryStringForm(obj);
    makePOSTRequest('includes/ajax/jskReferFriend.php', poststr, receiveReferFriend);
  }
    
  function receiveReferFriend() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        var nums = http_request.responseText.split(':sk:');
        
        updateAlertBox(nums[1], '', 1500);
        if (nums[0] == 1) {
          prevAlertBox = 'none';
        }
      }
    }
  }
  
  //This validation is for refer a friend page
  function valITIQRefer(frm) {
    var error = false;
    var message;
    
    if (isValidEmail(frm.elements['email'].value) == false) {
      message = "Error: Invalid email address, Your Email";    
      error = true;
    }
    
    if (frm.elements['name'].value == "") {
      message = "Error: Invalid Name, Please enter your name";
      error = true;
    }

    if (isValidEmail(frm.elements['femail'].value) == false)  {
      message = "Error: Invalid email address, Friends Email";    
      error = true;
    }

    if (frm.elements['fname'].value == "") {
      message = "Error: Invalid Name, Please enter your friend's name";
      error = true;
    }

    if (error != false) {
      alert(frm, message);
      return false;
    } else {
      return true;
    }
  }

/**
 * Process refer friend form using AJAX
 */
  function postITIQRefer(obj) {
    prevAlertBox = 'itiqReferBox';
    showHideBox('hide', 'itiqReferBox');
    // open up the loading alert. it has id tempAlert in it which is replaced after AJAX is called
    alert('', '<div id="tempAlert" style="text-align: left;">Sending email...<br/><br/><img style="margin: auto;" src="images/loading.gif" /></div>');
     
    var poststr = getQueryStringForm(obj);
    makePOSTRequest('includes/ajax/jskITIQRefer.php', poststr, receiveITIQRefer);
  }
    
  function receiveITIQRefer() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        
        var nums = http_request.responseText;
        
        if (nums == 0) {
          updateAlertBox("There was an error sending the email. Please check the email address, and try again", '', 1500);
        } else if (nums == 1) {
          updateAlertBox("Your email was sent successfully.");
          prevAlertBox = 'none';
        }
      }
    }
  }
  
  //This validation is for refer a friend page
  function validateReferAFriend(frm) {
    var error = false;
    var message;
    
    // convert both code fields to lowercase so they can be matched
    var code = frm.elements['code_refer'].value.toLowerCase();
    var secure_code = frm.elements['secure_code_refer'].value.toLowerCase();

    if (code != secure_code) {
      message = "Error: Security code does not match";
      error = true;
    }
    
    if(code == '') {
      message = "Error: Security code not valid";
      error = true;
    }

    if(isValidEmail(frm.elements['email'].value) == false) {
      message = "Error: Invalid email address, Your Email";    
      error = true;
    }
    
    if(frm.elements['name'].value == "") {
      message = "Error: Invalid Name, Please enter your name";
      error = true;
    }

    if(isValidEmail(frm.elements['femail'].value) == false)  {
      message = "Error: Invalid email address, Friends Email";    
      error = true;
    }

    if(frm.elements['fname'].value == "") {
      message = "Error: Invalid Name, Please enter your friend's name";
      error = true;
    }

    if (error != false) {
      alert(frm, message);
      return false;
    } else {
      return true;
    }
  }

  var validABN = false;
  
  // This validation is for Job Advertiser Registration Page
  function validateAdvertiserRegistration(frm) {
    var error = false;
    var message;

    if (frm.elements['first'].value == '') {
      message = "Error: Invalid First Name";
      error = true;
    }

    if (frm.elements['last'].value == '') {
      message = "Error: Invalid Last Name";
      error = true;
    }
    
    if (isAllValidEmail(frm.elements['email'].value) == false) {
      message = "Error: Invalid email address";
      error = true;
    }
    
    if (frm.elements['pass1'].value == '') {
      message = "Error: Invalid Password";
      error = true;
    }

    if (frm.elements['pass1'].value != frm.elements['pass2'].value) {
      message = "Error: Password does not match";
      error = true;
    }

    /* if a phone number entered in Daytime Phone, validate it
    if (frm.elements['contact'].value != '') {
      if(isValidPhone(frm.elements['contact'].value) == false) {
        message = "Error: Invalid daytime phone number. Please include your area code, without any spaces or brackets";
        error = true;
      }
    } */

    if (frm.elements['company'].value == "") {
      message = "Error: Invalid company name";
      error = true;
    }

    if (frm.elements['countryadv'].selectedIndex == 0) {
      message = "Error: Please select your country";
      error = true;
    }    
    
    if (frm.elements['locationadv'].selectedIndex == 0) {
      message = "Error: Please select your state";
      error = true;
    }

    if (frm.elements['suburb'].value == "")  {
      message = "Invalid suburb";
      error = true;
    }

    if (isInteger(frm.elements['post'].value) == false) {
      message = "Error: Invalid post code";
      error = true;
    } else if(frm.elements['post'].value.length != 4) {
      message = "Error: Invalid post code";
      error = true;
    }    

    if (frm.elements['address1'].value == "") {
      message = "Error: Invalid address";
      error = true;
    }  

    if (validABN == false) {
      message = "Error: The ABN that you entered was found to be invalid. Please check your records and try again"
      error = true;
    }

    /*
    if (isValidPhone(frm.elements['phone'].value) == false) {
      message = "Error: Invalid contact number. Please include your area code with no spaces";
      error = true;
    } */

    var code = frm.elements['code'].value.toLowerCase();
    var secure_code = frm.elements['secure_code'].value.toLowerCase();

    if(frm.elements['code'].value == "") {
      message = "Error: Security code not valid";
      error = true;
    }    
    
    if (code != secure_code) {
      message = "Error: Security code does not match";
      error = true;
    }
    
    if (frm.elements['agreement'].checked == false) {
      message = 'You must read and accept the Jobspeed User Agreement and Privacy Policy to become a member.';
      error = true;
    }

    if (error != false) {
      prevAlertBox = 'advertapp';
      showHideBox('hide', 'advertapp');
      alert(frm, message);
      return false;
    } else {
      return true;
    }
  }

/**
 * Process response from AJAX script
 * Display message, and return to registration box on error
 *
 * @param transport_response
 */

  function receiveAdvertiserApp() {
    var message = '';
    var error = false;

    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        result = http_request.responseText.split(':sk:');

        error = result[0];
        message = result[1];

        // output the response message to the alert box with a delay
        updateAlertBox(message, '', 1500);

        if (error == 0) {
          // don't go back to rego box on alert close
          prevAlertBox = 'none';
        }
      } else {
        alert('', 'There was a problem with the request.');
      } 
    }
  }

  function postAdvertiserApp(obj) {
    prevAlertBox = 'advertapp';
    showHideBox('hide', 'advertapp');
    // show loading alert
    alert('', 'Processing registration...<br/><br/><img style="margin: auto;" src="images/loading.gif" />');
    var poststr = getQueryStringForm(obj);
    makePOSTRequest('includes/ajax/advRegistration.php', poststr, receiveAdvertiserApp);
  }
  
/**
  * Validate the user registration form
  *
  * @param object frm Form object to validate
  * @return
  */
  function validateJobseeker(frm) {
    var error       = false;
    var message     = 'The following errors were encountered with your registration details:<ul style="text-align: left;margin-bottom:0px">';
    var code        = frm.elements['code'].value.toLowerCase();
    var secure_code = frm.elements['secure_code'].value.toLowerCase();
    
    if (frm.elements['first'].value == "") {
      message += "<li>Error: Invalid first name</li>";
      // frm.elements['first'].style.backgroundColor = 'yellow';
      // updateElement('first_error', '<img src="images/btn-help.jpg" title="Error: Invalid first name" />');
      error = true;
    }

    if (frm.elements['last'].value == "") {
      message += "<li>Error: Invalid last name</li>";
      // frm.elements['last'].style.backgroundColor = 'yellow';
      // updateElement('last_error', '<img src="images/btn-help.jpg" title="Error: Invalid last name" />');
      error = true;
    }

    if (isAllValidEmail(frm.elements['email'].value) == false) {
      message += "<li>Error: Invalid email address</li>";
      // frm.elements['email'].style.backgroundColor = 'yellow';
      // updateElement('email_error', '<img src="images/btn-help.jpg" title="Error: Invalid email address" />');
      error = true;
    }

    if (frm.elements['email'].value != frm.elements['email2'].value) {
      message += "<li>Error: Email address does not match</li>";
      // frm.elements['email2'].style.backgroundColor = 'yellow';
      // updateElement('email2_error', '<img src="images/btn-help.jpg" title="Error: Email addresses do not match" />');
      error = true;
    }

    if (frm.elements['pass1'].value == "") {
      message += "<li>Error: Invalid password</li>";
      // frm.elements['pass1'].style.backgroundColor = 'yellow';
      // document.getElementById('pass1_error').innerHTML = '<img src="images/btn-help.jpg" title="Error: Invalid password" />';
      error = true;
    }

    if (frm.elements['pass1'].value.length < 6) {
      message += "<li>Error: Password must be at least 6 characters</li>";
      // frm.elements['pass1'].style.backgroundColor = 'yellow';
      // updateElement('pass1_error', '<img src="images/btn-help.jpg" title="Error: Password must be at least 6 characters" />');
      error = true;
    }

    if (frm.elements['pass1'].value != frm.elements['pass2'].value) {
      message += "<li>Error: Passwords entered do not match</li>";
      // frm.elements['pass2'].style.backgroundColor = 'yellow';
      // updateElement('pass2_error', '<img src="images/btn-help.jpg" title="Error: Passwords do not match" />');
      error = true;
    } else {
      frm.elements['pass2'].style.backgroundColor = 'white';
    }

    if (frm.elements['code'].value == "") {
      message += "<li>Error: Security code not valid</li>";
      // frm.elements['code'].style.backgroundColor = 'yellow';
      // updateElement('code_error', '<img src="images/btn-help.jpg" title="Error: Security code not valid" />');
      error = true;
    } else {
      frm.elements['code'].style.backgroundColor = 'white';
    }

    if (code != secure_code) {
      message += "<li>Error: Security code does not match</li>";
      // frm.elements['code'].style.backgroundColor = 'yellow';
      // updateElement('code_error', '<img src="images/btn-help.jpg" title="Error: Security code does not match" />');
      error = true;
    } else {
      frm.elements['code'].style.backgroundColor = 'white';
    }

    if (frm.elements['agreement'].checked == false) {
      message += '<li>You must read and accept the Jobspeed User Agreement and Privacy Policy to become a member</li>';
      error = true;
    }

	message += '</ul>';
	
    if (error != false) {
      prevAlertBox = 'jobseekapp';
      showHideBox('hide', 'jobseekapp');
      alert(frm, message);
      return false;
    } else  {
      return true;
    }
  }

  function receiveJobseekerApp() {
    var error = 0;
    var message = '';

    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        result = http_request.responseText.split(':sk:');
        
        var error = result[0];
        var message = result[1];
        
        updateAlertBox(message, 'REGISTRATION SUCCESSFUL', 1500);
        
        if (error == 0) {
          // don't go back to rego box on alert close
          prevAlertBox = 'none';
        } 
      } else {
        alert('', 'There was a problem with the request.');
      } 
    }
  }

  function postJobseekerApp(obj) {
    prevAlertBox = 'jobseekapp';
    showHideBox('hide', 'jobseekapp');
    // show loading alert
    alert('', 'Processing registration...<br/><br/><img style="margin: auto;" src="images/loading.gif" />');
    var poststr = getQueryStringForm(obj);
    makePOSTRequest('includes/ajax/jskRegistration.php', poststr, receiveJobseekerApp);
  }

  //This validation is for Job Apply Page, User Logged In
  function jobapplyOnCheck(formName) {
    var formObj = eval('document.'+formName);
    var error_msg=false;
    var message_msg;  

    var code = formObj.code.value.toLowerCase();
    var secure_code = formObj.secure_code.value.toLowerCase();  

    if(code != secure_code) {
      message_msg = "Error: Security code does not match";
      error_msg = true;
    }
    
    if(formObj.code.value == "") {
      message_msg = "Error: Invalid security code";
      error_msg = true;
    }

    if(formObj.resumefile.value==0) {
      if(formObj.resume1.value.lastIndexOf(".doc")==-1 && formObj.resume1.value.lastIndexOf(".docx")==-1 && formObj.resume1.value.lastIndexOf(".rtf")==-1 && formObj.resume1.value.lastIndexOf(".txt")==-1 && formObj.resume1.value.lastIndexOf(".pdf")==-1 && formObj.resume1.value.lastIndexOf(".htm")==-1 && formObj.resume1.value.lastIndexOf(".html")==-1 && formObj.resume1.value.lastIndexOf(".ppt")==-1) {
        message_msg = "Error: Please choose correct file (pdf, txt, doc, rtf)";    
        error_msg = true;
      }
    }

    if(isAllValidEmail(formObj.emailaddress.value) == false) {
      message_msg = "Error: Invalid email address";    
      error_msg = true;
    }

    /* Phone validation turned off for now
    if (isInteger(formObj.phone.value) == false) {
      message_msg = "Error: Invalid phone number,Include area code";
      error_msg = true;
    } else if (formObj.phone.value.length < 10) {
      message_msg = "Error: Invalid phone number, Include area code";
      error_msg = true;
    }
    */
    if(formObj.lastname.value == "") {
      message_msg = "Error: Invalid last name";
      error_msg = true;
    }

    if(formObj.firstname.value == "") {
      message_msg = "Error: Invalid first name";
      error_msg = true;
    }

    if (error_msg!=false) {
      alert(formName, message_msg);
      return false;
    } else {
      return true;
    }
  }

/**
 * Match a filename against allowed file extensions
 *
 * @param string filename
 * @return boolean
 */
  function validateResumeFile(filename) {
    if (filename.lastIndexOf(".doc")  == -1 &&
        filename.lastIndexOf(".docx") == -1 &&
        filename.lastIndexOf(".rtf")  == -1 &&
        filename.lastIndexOf(".txt")  == -1 &&
        filename.lastIndexOf(".pdf")  == -1 &&
        filename.lastIndexOf(".htm")  == -1 &&
        filename.lastIndexOf(".html") == -1 &&
        filename.lastIndexOf(".ppt")  == -1) {
      return false;
    } else {
      return true;
    }
  }
  
  //This validation is for Job Apply Page, guest user
/**
 * Validate job application
 *
 * @param object formName - Form object to work with
 * @return boolean Successful
 */
  function jobapplyCheck(formName) {
    var formObj = eval('document.' + formName);
    var error_msg = false;
    var message_msg;

    var code = formObj.code.value.toLowerCase();
    var secure_code = formObj.secure_code.value.toLowerCase();  

    if(formObj.agreement.checked == false) {
      alert(formName, 'You must read and accept the Jobspeed User Agreement and Privacy Policy to become a member.');
      return false;
    }  

    if (formObj.resume2.value != "") {
      if (!validateResumeFile(formObj.resume2.value)) {
        message_msg = "Error: Please upload a resume in one of the following formats: doc, pdf, rtf, txt";
        error_msg = true;
      }
    } else {
      message_msg = "Error: Please upload a resume file to be sent with your application";
      error_msg = true;
    }

    if(code != secure_code) {
      message_msg = "Error: Security code does not match";
      error_msg = true;
    }

    if(formObj.code.value == "") {
      message_msg = "Error: Invalid security code";
      error_msg = true;
    }

    if(isValidEmail(formObj.emailadd.value) == false) {
      message_msg = "Error: Invalid email address";
      error_msg = true;
    }  

/* Opening up validation on phone number for international users
    if (isValidPhone(formObj.phone.value) == false) {
      message_msg = "Error: Invalid phone number. Please include your area code, with no spaces or brackets";
      error_msg = true;
    }
*/

    /*
    if (formObj.phone.value.length < 8) {
      message_msg = "Error: Invalid phone number. Not enough digits. Please include area code.";
      error_msg = true;
    }
    */
    
    if(formObj.last.value == "") {
      message_msg = "Error: Invalid last name";
      error_msg = true;
    }

    if(formObj.first.value == "") {
      message_msg = "Error: Invalid first name";
      error_msg = true;
    }

    if (error_msg == true) {
      alert(formName, message_msg);
      return false;
    } else {
      //ask them for password if they want to get registered
      fadePopupIn('passBox');
      hideSelects('visible');
      return false;
    }
  }

  //This validation is for Shortlisted Page, when user logged in
  function validateApplyA() {
    var error_msg = false;
    var message_msg;
    var code = document.jobapply3.code.value.toLowerCase();
    var secure_code = document.jobapply3.secure_code.value.toLowerCase();

    if (code != secure_code){
      message_msg = "Error: Security code does not match";
      error_msg = true;
    }

    if (document.jobapply3.code.value == '') {
      message_msg = "Error: Invalid security code";
      error_msg = true;
    }

    if(document.jobapply3.resumefile.value == 0) {
      if (!validateResumeFile(document.jobapply3.resume1.value)) {
        message_msg = "Error: Please choose correct file";
        error_msg = true;
      }
    }

    /*
    if (! isValidPhone(document.jobapply3.phone.value)) {
      message_msg = 'Error: Invalid phone number. Please input numbers only, including your area code (eg. 0292210000)';
      error_msg = true;
    }
    */

    if(isAllValidEmail(document.jobapply3.emailaddress.value) == false) {
      message_msg = "Error: Invalid email address";    
      error_msg = true;
    }

    if(document.jobapply3.lastname.value == '') {
      message_msg = 'Error: Invalid last name';
      error_msg = true;
    }

    if(document.jobapply3.firstname.value == '') {
      message_msg = 'Error: Invalid first name';
      error_msg = true;
    }

    if (error_msg != false) {
      alert('jobapply3', message_msg);
      return false;
    } else {
      var shortlistCheckListObj = document.getElementById('shortlistCheckList');
      if(shortlistCheckListObj.options.length < 1) {
        alert('jobapply3', "Please select the number of jobs you want to apply for.");
        return false;
      }

      // Prompt the user to apply for more than 1 job if they have only selected 1, and they have more than 1 in shortlist
      // totalcount needs to be larger than 2 because it is not being calculated correctly..
      if (shortlistCheckListObj.options.length == 1 && (document.jobapply3.totalcount.value > 2)) {
        confirm('jobapply3', 'Do you realise you can apply for more than one job at a time. Select multiple to maximise your chances. Do you still want to continue?', '');
        return false;
      } else {
        return true;
      }
    }
  }

/**
 * Validate a job application. Unregistered user, applying from SHORTLIST
 * 
 * @param none
 * @return boolean
 */
  function validateApplyOffline() {
    var error_msg = false;
    var message_msg;

    if(document.jobapply2.agreement.checked == false) {
      alert('jobapply2', 'You must read and accept the Jobspeed User Agreement and Privacy Policy to become a member.');
      return false;
    }  

    var code = document.jobapply2.code.value.toLowerCase();
    var secure_code = document.jobapply2.secure_code.value.toLowerCase();

    if(code != secure_code) {
      message_msg = "Error: Security code does not match";
      error_msg = true;
    }

    if(document.jobapply2.code.value == "") {
      message_msg = "Error: Invalid security code";
      error_msg = true;
    }

    if(document.jobapply2.resume2.value.lastIndexOf(".doc")==-1 && document.jobapply2.resume2.value.lastIndexOf(".docx")==-1 && document.jobapply2.resume2.value.lastIndexOf(".rtf")==-1 && document.jobapply2.resume2.value.lastIndexOf(".txt")==-1 && document.jobapply2.resume2.value.lastIndexOf(".pdf")==-1 && document.jobapply2.resume2.value.lastIndexOf(".htm")==-1 && document.jobapply2.resume2.value.lastIndexOf(".html")==-1 && document.jobapply2.resume2.value.lastIndexOf(".ppt")==-1) {
      message_msg = "Error: Please choose correct file";
      error_msg = true;
    }

/* ignore phone validation for now
    if (isInteger(document.jobapply2.phone.value) == false) {
      message_msg = "Error: Invalid phone number, Include area code";
      error_msg = true;
    } else if(document.jobapply2.phone.value.length < 10) {
      message_msg = "Error: Invalid phone number, Include area code";
      error_msg = true;
    }
*/
    /*
    if (document.jobapply2.phone.value < 8) {
      message_msg = "Error: Invalid phone number. Not enough digits. Please include area code.";
      error_msg = true;
    }
    */

    if(isAllValidEmail(document.jobapply2.emailadd.value) == false) {
      message_msg = "Error: Invalid email address";
      error_msg = true;
    }

    if(document.jobapply2.last.value == "") {
      message_msg = "Error: Invalid last name";
      error_msg = true;
    }

    if(document.jobapply2.first.value == "") {
      message_msg = "Error: Invalid first name";
      error_msg = true;
    }

    if (error_msg != false) {
      alert('jobapply2', message_msg);
      return false;
    } else {
      var shortlistCheckListObj = document.getElementById('shortlistCheckList');
      
      if(shortlistCheckListObj.options.length < 1) {
        alert('jobapply2', "Please select the number of jobs you want to apply for.");
        return false;
      }

      if(shortlistCheckListObj.options.length == 1 && (document.jobapply2.totalcount.value > 1)) {
        confirm("jobapply2", 'Do you realise you can apply for more than one job at a time. Select multiple to maximise your chances. Do you still want to continue?', "register");
        return false;
      } else {
        fadePopupIn('passBox');
        hideSelects('visible');
        return false;
      }
    }
  }

//this function is for file validation in resume management section
  function validateFile() {
    var error_msg=false;
    var message_msg;  
  
    if (document.browse.resume.value.lastIndexOf(".doc") == -1 &&
        document.browse.resume.value.lastIndexOf(".docx") == 1 &&
        document.browse.resume.value.lastIndexOf(".rtf")==-1 &&
        document.browse.resume.value.lastIndexOf(".txt")==-1 &&
        document.browse.resume.value.lastIndexOf(".pdf")==-1 && 
        document.browse.resume.value.lastIndexOf(".htm")==-1 && 
        document.browse.resume.value.lastIndexOf(".html")==-1 &&
        document.browse.resume.value.lastIndexOf(".ppt")==-1) {
          message_msg = "Error: Please choose correct file";    
          error_msg = true;
      }  

    if (error_msg!=false) {
      //alert('browse', message_msg);
      return false;
    } else {
      document.browse.submit();
    }
  }

//this function is to validate image extensions in upload logo
  function validateImageFile() {
    var error_msg = false;
    var message_msg;  
  
    filename = document.browse.adslogo.value.toLowerCase();
    
    if (filename.lastIndexOf(".png")  == -1 &&
        filename.lastIndexOf(".jpg")  == -1 &&
        filename.lastIndexOf(".jpeg") == -1 &&
        filename.lastIndexOf(".gif")  == -1) {
      message_msg = "Error: Unsupported file type. Please upload an image in either JPEG, GIF or PNG format";
      error_msg = true;
    } 
    
    if (error_msg != false) {
      parent.alert('', message_msg);
      return false;
    } else {
      document.browse.submit();
    }
  }

  function orderByCheckDraft(formid,count,pageLink) {
    var formObj = eval('document.'+formid);
    for (var i = 1; i <= count;i ++) {
      if(eval('formObj.publish' + i + '.checked') || eval('formObj.edit'+i+'.checked') || eval('formObj.archive' + i + '.checked') || eval('formObj.delete' + i + '.checked')){
        //alert('renew'+i + ' is checked');
        alert(formid, 'You cannot change order while jobs are selected');
        return false;
      }
    }
    // window.location = pageLink;
    countries.loadajaxpage(pageLink);
    return true;
  }

/**
 * This function checks whether the user agreement / privacy policy has been agreed to
 *
 * @param object formName The name of the form which we are checking
 */
  function agreementCheck(formName) {
    var formObj = eval('document.'+formName);
    if(formObj.agreement.checked == false) {
      alert(formName, 'You must read the user agreement and privacy policy.');
      return false;
    }  
    return true;
  }

/**
 * This function checks the status of the AUS citizen check when shortlisting / applying for a job
 *
 * @param int job_id
 * @param string value
 * @param action
 */
  function checkstatus(job_id, value, action) {
    //var formObj = eval('document.'+applyjobs);
    if(document.applyjobs.status.checked == false) {
      if (value == "Australian citizens only") {
        alert('applyjobs', 'You must be an Australian Citizen to apply for this job.');
        return false;
      } else if(value == "Australian residents only") {
        alert('applyjobs', 'You must be an Australian Resident to apply for this job.');
        return false;
      } else {
        alert('applyjobs', 'You must be an Australian Citizen/Resident to apply for this job.');
        return false;
      }
    } else {
      if (action == 1) {
        shortListEffect();
        checkListCheck();
		showShortListed(job_id);
      }
      
      return true;
    }
  }
  
    function validateFNameAdv(fNameId) {
      fName = document.getElementById(fNameId);
      if (fName.value.length > 1) {
        updateElement('validFirstName', validationTick('First name valid'));
      } else {
        document.getElementById('validFirstName').innerHTML = '*';
      }
    }

    function validateLNameAdv(lNameId) {
      lName = $(lNameId);
      if (lName.value.length > 1) {
        updateElement('validLastName', validationTick('Last name valid'));
      } else {
        // updateElement('validLastName', validationCross('Last name invalid'));
        updateElement('validLastName', '*');
      }
    }

    function validateLoginEmail(emailFieldID) {
      email = document.getElementById(emailFieldID);
      if (isValidEmail(email.value)) {
        makePOSTRequest('includes/ajax/validateEmail.php', 'email=' + email.value, receiveEmailValidation);
      } else {
        // document.getElementById('validEmail').innerHTML = '';
        return false;
      }
    }
    
    function validationTick(message) {
      return '<img src="images/img-green_tick.gif" alt="" title="' + message + '" />';
    }
    
    function validationCross(message) {
      return '<img src="images/img-red_cross.gif" alt="" title="' + message + '" />';
    }

    function receiveEmailValidation() {
      if (http_request.readyState == 4) {
        if (http_request.status == 200) {
          if (http_request.responseText == 'Success') {
            updateElement('validEmail', validationTick('Email address is valid'));
          } else {
            updateElement('validEmail', validationCross('The email address you entered is either invalid, or already in use. Please enter a different email'));
          }
        }
      }
    }
    
    function validatePassword(pass1Id) {
      pass1 = document.getElementById(pass1Id);
      if (pass1.value.length < 6) {
        updateElement('validPassword', validationCross('The password you entered is too short. Please enter a longer password'));
      } else {
        updateElement('validPassword', validationTick('Your password is valid'));
      }
    }

    function validatePasswordConf(pass1Id, pass2Id) {
      pass1 = document.getElementById(pass1Id);
      pass2 = document.getElementById(pass2Id);
      
      if (pass1.value.length >= 6) {
        if (pass1.value != pass2.value) {
          updateElement('validPasswordConfirm', validationCross('The passwords you entered do not match'));
        } else {
          updateElement('validPasswordConfirm', validationTick('Your passwords match.'));
        }
      } else {
        updateElement('validPasswordConfirm', validationCross('The password you entered is too short. Please enter a longer password'));
      }
    }
    
    function validateABN() {
      abn = document.getElementById('abn');
      if (abn.value.length < 11) {
        updateElement('validABN', '*');
        return false;
      } else {
        makePOSTRequest('includes/ajax/validateABN.php', 'abn=' + abn.value, receiveABNValidation);
      }
    }
    
    function receiveABNValidation() {
      if (http_request.readyState == 4) {
        if (http_request.status == 200) {
          if (http_request.responseText == 'Success') {
            updateElement('validABN', validationTick('Your ABN has been validated'));
            validABN = true;
          } else {
            updateElement('validABN', validationCross('Your ABN is invalid. Please check your records, and try again.'));
          }
        }
      }
    }
  
  function animateElement(elementId) {
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'red\'', 500);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'black\'', 1000);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'red\'', 1500);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'black\'', 2000);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'red\'', 2500);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'black\'', 3000);
    setTimeout('document.getElementById(\'' + elementId + '\').style.color = \'red\'', 3500);
  }

  function checkForgottenPassword(email, firstname) {

    if (isAllValidEmail(email) == false) {
      message = "Error: Invalid email address";    
      prevAlertBox = 'forgotPassBox';
      showHideBox('hide', 'forgotPassBox');
      alert('', message);
      return false;
    } else if (firstname != '' && firstname != null) {
      
      xmlHttp = GetXmlHttpObject();
    
      if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return;
      }
      var url = "includes/ajax/check_email.php";
      url = url + "?email=" + email;
      url = url + "&firstname=" + firstname;
      url = url + "&sid=" + Math.random();
      xmlHttp.onreadystatechange = stateCheckForgottenPassword;
      xmlHttp.open("GET", url, true);
      xmlHttp.send(null);
    } else {
      alert('', 'You did not enter your first name');
    }
  }

  function stateCheckForgottenPassword() {
    
    if (xmlHttp.readyState == 4) {
      if (xmlHttp.status == 200) {
    
        var nums = xmlHttp.responseText.split(':sk:');
        if (nums[0] == 1) {
          return emailForgottenPassword(document.forgot_form.email.value);
        } else {
          //showHideBox('hide', 'forgotPassBox');
          prevAlertBox = 'forgotPassBox';
          showHideBox('hide', 'forgotPassBox');
          alert('', nums[1]);
          return false;
        }
      }
    }
  }

/**
 * Reset the password for given email address and send an email to the user
 *
 * @param string email Email address to reset password for
 * @return boolean
 */
  function emailForgottenPassword(email) {

    xmlHttp = GetXmlHttpObject();
    
    if (xmlHttp == null) {
      alert ("Your browser does not support AJAX!");
      return;
    }

    var url = "includes/ajax/reset_password.php";
    url = url + "?email=" + email;
    url = url + "&sid=" + Math.random();
    xmlHttp.onreadystatechange = stateEmailForgottenPassword;
    xmlHttp.open("GET", url, true);
    xmlHttp.send(null);
  }

  function stateEmailForgottenPassword() {

    if (xmlHttp.readyState == 4) {

      var nums = xmlHttp.responseText.split(':sk:');
      if (nums[0] == 0) {
        prevAlertBox = 'forgotPassBox';
        showHideBox('hide', 'forgotPassBox');
        alert('', nums[1]);
        return false;
      } else if (nums[0] == 1) {
        prevAlertBox = 'none';
        showHideBox('hide', 'forgotPassBox');
        alert('', nums[1]);
        return true;
      }
    }
  }
