// JavaScript Document
/*
Description :        This page contains all the different javascript functions for the PurplePassport Website
Exceptions :        If a javascript function needs some server side code, then it will be run on the page itself
*/
//*******************************

// form (AddEditCourseStep1.asp) validation function //

function validateAddEditCourseStep1(form) {

  var txtTitle = courseForm.txtTitle.value;
  var selTraining = courseForm.selTraining.value;
  var selAwarding = courseForm.selAwarding.value;
  var selLevel = courseForm.selLevel.value;
  var txtHours = courseForm.txtHours.value;
  var txtPISDate = courseForm.txtPISDate.value;
  var selStatus = courseForm.selStatus.value;

  var nameRegex = /^[a-zA-Z]+(([\'\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
  var hoursRegex = /[0-9]^[a-zA-Z]/;
  
  
  if(txtTitle == "") {

       inlineMsg('txtTitle','You must enter the course title.',2);
       return false
  }
  if(selAwarding == 0) 
  {
    inlineMsg('selAwarding','<strong>Error</strong><br />You must select the Awarding Body.',2);
    return false;
  }
      
  /*
  if(!txtTitle.match(nameRegex)) {
    inlineMsg('txtTitle','You have entered an invalid course title.',2);
    return false;
  }
  */
   if(txtHours == "") {
    inlineMsg('txtHours','You must enter the amount of course hours.',2);
    return false;
  }

  if(selTraining == 0) {
    inlineMsg('selTraining','<strong>Error</strong><br />You must select the course type.',2);
    return false;
  }

  if(selLevel == 0) {
    inlineMsg('selLevel','<strong>Error</strong><br />You must select the course level.',2);
    return false;
  }

  if(txtPISDate != "") {
    if (isDate(txtPISDate) == false){
        inlineMsg('txtPISDate','You must enter the correct Renewal Date. Match dd/mm/yyyy',2);
        return false;
    }
  }
//  else {
//        inlineMsg('txtPISDate','You must enter the Renewal Date',2);
//        return false;
//  }

  if(selStatus == 0) {
    inlineMsg('selStatus','<strong>Error</strong><br />You must select the status.',2);
    return false;
  }

  return true;
}

// START OF ALERT MESSAGE //

var MSGTIMER = 30;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;

// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
  var msg;
  var msgcontent;
  if(!document.getElementById('msg')) {
    msg = document.createElement('div');
    msg.id = 'msg';
    msgcontent = document.createElement('div');
    msgcontent.id = 'msgcontent';
    document.body.appendChild(msg);
    msg.appendChild(msgcontent);
    msg.style.filter = 'alpha(opacity=0)';
    msg.style.opacity = 0;
    msg.style.position = 'absolute';
    msg.className = 'RedText';
    msg.alpha = 0;
  } else {
    msg = document.getElementById('msg');
    msgcontent = document.getElementById('msgcontent');
  }
  msgcontent.innerHTML = string;
  msg.style.display = 'block';
  var msgheight = msg.offsetHeight;
  var targetdiv = document.getElementById(target);
  targetdiv.focus();
  var targetheight = targetdiv.offsetHeight;
  var targetwidth = targetdiv.offsetWidth;
  var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
  var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
  msg.style.top = topposition + 'px';
  msg.style.left = leftposition + 'px';
  clearInterval(msg.timer);
  msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
  if(!autohide) {
    autohide = MSGHIDE;
  }
  window.setTimeout("hideMsg()", (autohide * 1000));
}

// hide the courseForm alert //
function hideMsg(msg) {
  var msg = document.getElementById('msg');
  if(!msg.timer) {
    msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
  }
}

// face the message box //
function fadeMsg(flag) {
  if(flag == null) {
    flag = 1;
  }
  var msg = document.getElementById('msg');
  var value;
  if(flag == 1) {
    value = msg.alpha + MSGSPEED;
  } else {
    value = msg.alpha - MSGSPEED;
  }
  msg.alpha = value;
  msg.style.opacity = (value / 100);
  msg.style.filter = 'alpha(opacity=' + value + ')';
  if(value >= 99) {
    clearInterval(msg.timer);
    msg.timer = null;
  } else if(value <= 1) {
    msg.style.display = "none";
    clearInterval(msg.timer);
  }
}

// calculate the position of the element in relation to the left of the browser //
function leftPosition(target) {
  var left = 0;
  if(target.offsetParent) {
    while(1) {
      left += target.offsetLeft;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.x) {
    left += target.x;
  }
  return left;
}

// calculate the position of the element in relation to the top of the browser window //
function topPosition(target) {
  var top = 0;
  if(target.offsetParent) {
    while(1) {
      top += target.offsetTop;
      if(!target.offsetParent) {
        break;
      }
      target = target.offsetParent;
    }
  } else if(target.y) {
    top += target.y;
  }
  return top;
}

// preload the arrow //
if(document.images) {
  arrow = new Image(7,80);
  arrow.src = "images/msg_arrow.gif";
}

// END OF ALERT MESSAGE //

// form (AddEditCourseStep2.asp) validation function //
function validateAddEditCourseStep2(form) {

//  var txtTarget = courseForm.txtTarget.value;
//  var txtCPReq = courseForm.txtCPReq.value;
//  var txtEntryReq = courseForm.txtEntryReq.value;
//  var txtCertification = courseForm.txtCertification.value;
//  var txtProgression = courseForm.txtProgression.value;
//  var txtTopics = courseForm.txtTopics.value;
//  var txtMethods = courseForm.txtMethods.value;
//  var selRegions = courseForm.selRegions.value;

//  if(txtTarget == "") {
//    inlineMsg('txtTarget','You must enter the target candidates.',2);
//    return false;
//  }

//  if(txtCPReq == "") {
//    inlineMsg('txtCPReq','You must enter the delivery requirements.',2);
//    return false;
//  }

//  if(txtEntryReq == "") {
//    inlineMsg('txtEntryReq','You must enter the entry requirements.',2);
//    return false;
//  }

//  if(txtCertification == "") {
//    inlineMsg('txtCertification','You must enter the certification.',2);
//    return false;
//  }

//  if(txtProgression == "") {
//    inlineMsg('txtProgression','You must enter the opportunities for progression.',2);
//    return false;
//  }

//  if(txtTopics == "") {
//    inlineMsg('txtTopics','You must enter the topics and areas of study.',2);
//    return false;
//  }

//  if(txtMethods == "") {
//    inlineMsg('txtMethods','You must enter the assessment and methods that are used.',2);
//    return false;
//  }

//  var selRegions = courseForm.selRegions.value;
//  if(selRegions == 0) {
//    inlineMsg('selRegions', 'You must select the region.',2);
//    return false;
//  }
  courseForm.submit();
  return true;
}

// form (AddNewProviderDetails.asp) validation function //
function validateAddNewProviderDetails(form) {


  var txtFreeText = document.getElementById('txtFreeText').value;
  var txtAddr = document.getElementById('txtAddr').value;
  var txtPostCode = document.getElementById('txtPostCode').value;
  var txtSkills = document.getElementById('txtSkills').value;
  var txtCodeOfPractice = document.getElementById('txtCodeOfPractice').value;
  var txtKeyContact = document.getElementById('txtKeyContact').value;
  var txtPhone = document.getElementById('txtPhone').value;
  var txtEmail = document.getElementById('txtEmail').value;
  var txtWebAddr = document.getElementById('txtWebAddr').value;

  var emailRegex = /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/;
  var numbRegex = /[0-9]^[a-zA-Z]/;
  
  var result = true;

  if(txtFreeText == '') {
    inlineMsg('selProvider', 'You must enter New provider`s name',2);
    result = false;
  }
  alert; 
  if(txtAddr == '') {
    inlineMsg('txtAddr','You must enter the address',2);
    result = false;
  }

  if(txtPostCode == '') {
    inlineMsg('txtPostCode','You must enter the post code',2);
    result = false;
  }
  
  if(postit(document.getElementById('txtPostCode')) == false)
  {
    inlineMsg('txtPostCode','You have entered an invalid postcode',2);
    result = false;
  }
  
  if(txtPhone == '') {
    inlineMsg('txtPhone','You must enter the phone no.',2);
    result = false;
  }

  if(txtEmail == '') {
    inlineMsg('txtEmail','You must enter the email.',2);
    result = false;
  }

  if(!txtEmail.match(emailRegex))  
  {
    inlineMsg('txtEmail','You have entered an invalid email',2);
    result = false;
  }

  return result;
}
// end form (AddNewProviderDetails.asp) validation function //


function postit(postcodeField)
{ //check postcode format is valid
  var test = postcodeField.value;
  var size = test.length;  
  test = test.toUpperCase(); //Change to uppercase
  while (test.slice(0,1) == ' ') //Strip leading spaces
  {
    test = test.substr(1,size-1);size = test.length;
  }
  while(test.slice(size-1,size)== ' ') //Strip trailing spaces
  {
    test = test.substr(0,size-1);size = test.length;
  }
  postcodeField.value = test; //write back to form field
  if (size < 6 || size > 8)
  { //Code length rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - wrong length", 2);
    postcodeField.focus();
    return false;
  }
  if (!(isNaN(test.charAt(0))))
  { //leftmost character must be alpha character rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - cannot start with a number", 2);
    postcodeField.focus();
    return false;
  }
  if (isNaN(test.charAt(size-3)))
  { //first character of inward code must be numeric rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - alpha character in wrong position",2);
    postcodeField.focus();
    return false;
  }
  if (!(isNaN(test.charAt(size-2))))
  { //second character of inward code must be alpha rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - number in wrong position",2);
    postcodeField.focus();
    return false;
  }
  if (!(isNaN(test.charAt(size-1))))
  { //third character of inward code must be alpha rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - number in wrong position",2);
    postcodeField.focus();
    return false;
  }
  if (!(test.charAt(size-4) == " "))
  {//space in position length-3 rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - no space or space in wrong position",2);
    postcodeField.focus();
    return false;
   }
  count1 = test.indexOf(" ");count2 = test.lastIndexOf(" ");
  if (count1 != count2)
  {//only one space rule
    inlineMsg('txtPostCode', test + " is not a valid postcode - only one space allowed",2);
    postcodeField.focus();
    return false;
  }
  return true;
}

// form (FindCourseToEdit.asp) validation function //
function validateFindCourseToEdit(form) {

  var txtKeyWord = formFindCourseToEdit.txtKeyWord.value;
  var txtFrom = formFindCourseToEdit.txtFrom.value;
  var txtTo = formFindCourseToEdit.txtTo.value;
/*
  if(txtKeyWord == "") {
    inlineMsg('txtKeyWord','You must enter the key word',2);
    return false;
  }

  if(selCourse == 0) {
    inlineMsg('selCourse', 'You must select the training course or qualification',2);
    return false;
  }

  if(selStatus == 0) {
    inlineMsg('selStatus', 'You must select the status',2);
    return false;
  }

  if(selRegion == 0) {
    inlineMsg('selRegion', 'You must select the region',2);
    return false;
  }

 */
  if(txtFrom != "") {
    if (isDate(txtFrom) == false){
        inlineMsg('txtTo','You must enter the date from which want start the search. Match dd/mm/yyyy',2);
        return false;
    }
  }
  else {
        inlineMsg('txtTo','You must enter the date from which want start the search',2);
        return false;
  }

  if(txtTo != "") {
    if (isDate(txtTo) == false){
        inlineMsg('txtTo','You must enter the end date. Match dd/mm/yyyy',2);
        return false;
    }
  }
  else {
        inlineMsg('txtTo','You must enter end date',2);
        return false;
  }

  return true;
}

// end form (FindCourseToEdit.asp) validation function //


function validateFindUserCourse(form) {

  var txtKeyWord = formFindCourseToEdit.txtKeyWord.value;


  //if(txtKeyWord == '') {
  //  inlineMsg('txtKeyWord','You must enter the key word',2);
  //  return false;
  //}

  return true;
}



//only numeric
function onlyNumeric(event) {

  if (((event.keyCode > 47) && (event.keyCode < 58)) || ( (event.keyCode == 46) || (event.keyCode == 35) || (event.keyCode == 33) || (event.keyCode == 8) || (event.keyCode == 36) || (event.keyCode == 39) || (event.keyCode == 40) || (event.keyCode == 37) || (event.keyCode == 38)|| (event.keyCode == 96) ||(event.keyCode == 97) || (event.keyCode == 98) || (event.keyCode == 99) || (event.keyCode == 100) || (event.keyCode == 101) || (event.keyCode == 102) || (event.keyCode == 103) || (event.keyCode == 104) || (event.keyCode == 105))){
      event.returnValue = true;
          return true;

  }else{
          event.returnValue = false;
          return false;
  }
}

function leaveOnlyNumeric(element){
  var oldVal =  element.value;
  var newVal = "";
  var re = new RegExp(/[0-9]/);
  var temp;
  for (i=0; i <= oldVal.length; i++){

          temp = oldVal.charAt(i);
          if (temp.match(re)){
                  newVal+=oldVal.charAt(i);
          }
  }
  element.value = newVal;
}

/* document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names,
     class names and ids and can be nested. For example:

       elements = document.getElementsBySelect('div#main p a.external')

     Will return an array of all 'a' elements with 'external' in their
     class attribute that are contained inside 'p' elements that are
     contained inside the 'div' element which has id="main"


   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails
*/

function zebraTable(selector, zebraClass){
    var el = document.getElementsBySelector(selector);
    if (el == false) return;
    var zebra = false;
        for (var i = 0; i < el.length; i++) {
        if (zebra == true) el[i].className = zebraClass;
                (zebra == true) ? zebra = false : zebra = true;
        }
    }
    
    function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}
    
    
    
 function validateQuickSearch(form) {

  
 if (formQuickSearch.ShowAllByLevel != null )
  document.getElementById("ShowAllByLevel").value = 0;
  
 if (formQuickSearch.ShowAllByStatus != null )
  formQuickSearch.ShowAllByStatus.value = 0;
 
 if (formQuickSearch.ShowAllByLevel2 != null )
  formQuickSearch.ShowAllByLevel2.value = 0;
 
 if (formQuickSearch.ShowAllByStatus2 != null )
  formQuickSearch.ShowAllByStatus2.value = 0;

  return true;
}  
  
function validateQuickSearch1(form) {
  var ShowAllByLevel = formQuickSearch.ShowAllByLevel.value;  

 if (formQuickSearch.ShowAllByStatus != null )
  formQuickSearch.ShowAllByStatus.value = 0;

  if (formQuickSearch.ShowAllByLevel2 != null )
    formQuickSearch.ShowAllByLevel2.value = 0;

  if (formQuickSearch.ShowAllByStatus2 != null)  
    formQuickSearch.ShowAllByStatus2.value = 0;
  
  
  if(ShowAllByLevel == 0) {
    inlineMsg('ShowAllByLevel','<strong>Error</strong><br />You must select the course level.',2);
    return false;
  }

  return true;
}  
    
function validateQuickSearch2(form) {
  var ShowAllByStatus = formQuickSearch.ShowAllByStatus.value;
  
 if (formQuickSearch.ShowAllByLevel != null )
  formQuickSearch.ShowAllByLevel.value = 0;
 
 if (formQuickSearch.ShowAllByLevel2 != null )
  formQuickSearch.ShowAllByLevel2.value = 0;
 
 if (formQuickSearch.ShowAllByStatus2 != null )
  formQuickSearch.ShowAllByStatus2.value = 0;


  if(ShowAllByStatus == 0) {
    inlineMsg('ShowAllByStatus','<strong>Error</strong><br />You must select the status.',2);
    return false;
  }

  return true;
}    
    
function validateQuickSearch3(form) {
  var ShowAllByLevel2 = formQuickSearch.ShowAllByLevel2.value;
  var ShowAllByStatus2 = formQuickSearch.ShowAllByStatus2.value;
  
   if (formQuickSearch.ShowAllByLevel != null )
  formQuickSearch.ShowAllByLevel.value = 0;
  
   if (formQuickSearch.ShowAllByStatus != null )
  formQuickSearch.ShowAllByStatus.value = 0;


  if(ShowAllByLevel2 == 0) {
    inlineMsg('ShowAllByLevel2','<strong>Error</strong><br />You must select the course level.',2);
    return false;
  }

  if(ShowAllByStatus2 == 0) {
    inlineMsg('ShowAllByStatus2','<strong>Error</strong><br />You must select the status.',2);
    return false;
  }

  return true;
}

function validateQuickSearchForm(form, button)
{
  var selLvl = document.getElementById('ShowAllByLevel').value;
  var selStat = document.getElementById('ShowAllByStatus').value;
  
  
  var selReg = (document.getElementById('ShowAllByRegion') != null ? true : false);
 
  var selStat2 = -1;
  var selLvl2 = -1;

  var isAvSelLvl2 = (document.getElementById('ShowAllByLevel2') != null ? true : false);  
  if (isAvSelLvl2) selLvl2 = document.getElementById('ShowAllByLevel2').value;

  var isAvSelStat2 = (document.getElementById('ShowAllByStatus2') != null ? true : false);
  if (isAvSelStat2) selStat2 = document.getElementById('ShowAllByStatus2').value;
  
  var line;
  var msg = "";

  if (button == 'submit1') {msg = ''}
  else if (button == 'submit2')
  {
    if (selLvl == '0')
    {
        msg = 'You must select the course level';    
        line = 'submit2';
    }
  }
  else if (button == 'submit3')
  {
    if (selStat == '0')
    {
        msg = 'You must select the status';
        line = 'submit3';
    }
  }
  else if (button == 'submit4')
  {
    if ((isAvSelLvl2) && (selLvl2 == '0'))
    {
        msg = 'You must select the course level';
        line = 'submit4';
    }
    else if ((isAvSelStat2) && (selStat2 == '0'))
    {
        msg = 'You must select the status';
        line = 'submit4';
    }    
  }
  else if (button == 'submit5')
  {
    if (selReg == '0')
    {
        msg = 'You must select the Region';    
        line = 'submit5';
    }
  }

  if (msg == '') return true;
  else
  {
    inlineMsg(line,'<strong>Error</strong><br />'+msg+'.',2);
    return false;
  }
}