var $C = YAHOO.util.Connect;
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;

// declare namespace for calendar control
YAHOO.namespace("calendarControl");

var myPostEvent = function (e) {
	var before, after, delay, elapsed, remaining, redirect, e;
	// specify the redirect page
	redirect = './thanks.html';
	// specify time delay for the progress bar display
	delay = 2000;
	
	// redirect page helper function
	var redirectPage = function() {
		// renable submit button
		document.getElementById("submitApplication").disabled = false;
		// redirect to thanks page
		window.location = redirect;
	};	// end of redirect page helper function
		
	// upload case handler
	var handleUpload = function(o) {
		e = o;
		// capture current time again to calculate time elapsed
		after = new Date();
		elapsed = parseInt(after.getTime()) - parseInt(before.getTime());

		// close progress bar based time elapsed
		if (elapsed < delay)	{
			// close the progress bar, then redirect
			remaining = delay - elapsed;
			setTimeout(function(o) {
				pnlWait.hide();
				redirectPage();
				}, remaining);									
		}
		else	{
			pnlWait.hide();
			redirectPage();
		}	// end of close progress bar based time elapsed
	};	// end of upload case handler

	// callback function
	var callback = {
		// upload handler
		upload: handleUpload
	};	// end of callback function


	// disable submit button
	document.getElementById("submitApplication").disabled = true;

	// capture current time to calculate time elapsed later
	before = new Date();

	// show the wait panel
	var pnlWait = new YAHOO.widget.Panel("wait",
																								{ width:"240px",
																									fixedcenter:true,
																									close:false,
																									draggable:false,
																									modal:true,
																									visible:false,
																									effect:{effect:YAHOO.widget.ContainerEffect.FADE, duration:0.5}
																								} );
	pnlWait.setHeader("Please wait while we upload your application...");
	pnlWait.setBody('<img src="./images/uploading.gif" />');
	pnlWait.render(document.body);
	pnlWait.show();

	// override the default behaviour of form posting
	$E.preventDefault(e);
	// argument formId can be the id or name attribute value of the
	// HTML form, or an HTML form object.
	var formObject = document.getElementById('appForm');
	YAHOO.util.Connect.setForm(formObject, true);
	
	var cObj = $C.asyncRequest('POST', './scripts/ess-formmail/ess-formmail.asp', callback);
}
//$E.addListener("submitApplication", "click", myPostEvent);

var finePrintAcceptance = function(e) {
	var actionDiv = $D.get("ac");  
	var elTarget = $E.getTarget(e);
	if (elTarget.checked == true) {
		$D.setStyle(actionDiv, "visibility", "visible");  
	}
	else {
		$D.setStyle(actionDiv, "visibility", "hidden");  
	}
}

$E.addListener("finePrintAcceptance", "click", finePrintAcceptance);

var initializeForm = function() {
	// show the TabControl
	$D.removeClass("nav", "blank");
	
	// hide the submit button
	$D.setStyle("ac", "visibility", "hidden");
	
	// hide section label
	$D.setStyle(["hdPersonal", "hdAvailability", "hdAboutyou", "hdFineprint"], "display", "none");
  
	/* show the navigation panel */
	$D.setStyle("topPanel", "visibility", "visible");
  document.getElementById("btnPrev").disabled = true;
  document.getElementById("btnNext").disabled = false;
};

YAHOO.example.init = function() {
  var intTabIndex = 0;
	var tabView = new YAHOO.widget.TabView('applicationForm', {activeIndex: intTabIndex});

  tabView.on('contentReady', function() {
          this.getTab(0).set('activationEvent', ["btnPrev","btnNext"]);
          this.getTab(1).set('activationEvent', ["btnPrev","btnNext"]);
          this.getTab(2).set('activationEvent', ["btnPrev","btnNext"]);
          this.getTab(3).set('activationEvent', ["btnPrev","btnNext"]);
          });

  var buttonClick = function(ev) {
    var retValue = true;
    var currentTabIndex;
    var strErr = '';
  
    /* Identify the tab that triggered the event */  
    var tar = $E.getTarget(ev);
    var strButton = trimAll(tar.value);
  
    currentTabIndex = tabView.get('activeIndex');
    /* END of identifying triggering tab */

  
    /* Validate fields within the tab */
    switch(currentTabIndex) {
      case 0: /* Star Profile (Personal Details) */
        retValue = validatePersonalDetails(document);
        // disable specific fields under 'Show Times' (Availability) tab
        if (retValue)
          disableAvailability(document);
        break;
        
      case 1: /* Showtimes (Availability) */
        retValue = validateAvailability(document);
        break;
        
      case 2: /* Character Notes (About You) */
        retValue = validateAboutYou(document);
        break;
        
      case 3: /* Character Notes (About You) */
        retValue = true;
        break;
        
      default:
        ;
    } /* END of fields validation */
  
    /* Make Tab transition only when validation succeeded */
    if (retValue) {
      // determine new tab index for 'Next' button click
      if( (strButton.toLowerCase() == 'next') && (currentTabIndex != 3) )
        currentTabIndex++;
      // determine new tab index for 'Prev' button click
      else if ( (strButton.toLowerCase() == 'prev') && (currentTabIndex != 0) )
        currentTabIndex--;

      // carry out the tab transition  
      tabView.set('activeIndex', currentTabIndex);
  
      // enable/disable 'Prev' or 'Next' buttons according to tabs
      // disable 'Prev' button for 'Star Profile' tab
      if (currentTabIndex == 0) {
        document.getElementById("btnPrev").disabled = true;
        document.getElementById("btnNext").disabled = false;
      }
      // disable 'Next' button for 'It's a Wrap' tab
      else if (currentTabIndex == 3) {
        document.getElementById("btnPrev").disabled = false;
        document.getElementById("btnNext").disabled = true;
      }
      // enable both buttons for the other tabs
      else {
        if (document.getElementById("btnPrev").disabled)
          document.getElementById("btnPrev").disabled = false;

        if (document.getElementById("btnNext").disabled)
          document.getElementById("btnNext").disabled = false;
      }
    } /* END of Tab transition */
  
    return retValue;
  }            

  $E.addListener(["btnNext","btnPrev"], "click", buttonClick );	  
};  /* END of YAHOO.example.init function */

YAHOO.example.init();

  
// client side validation methods
function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.

PARAMETERS: Source string from which spaces will
  be removed;

RETURNS: Source string with whitespaces removed.
*************************************************/
 var objRegExp = /^(\s*)$/;

    //check for all spaces
    if(objRegExp.test(strValue)) {
       strValue = strValue.replace(objRegExp, '');
       if( strValue.length == 0)
          return strValue;
    }

   //check for leading & trailing spaces
   objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
   if(objRegExp.test(strValue)) {
       //remove leading and trailing whitespace characters
       strValue = strValue.replace(objRegExp, '$2');
    }
  return strValue;
}

function validateTextInput(el,label) {
  var strErr = '';
  var strInput = trimAll(el.value);
 
  // check for null value
  if (strInput == null) {
    strErr =  label + ' cannot be null!';
  }
  // check for empty string
  else if (strInput.length < 1) {
    strErr =  label + ' cannot be blank!';
  }
  // check for embedded script tag
  else if ( ( strInput.indexOf("<") != -1 ) || ( strInput.indexOf(">") != -1 ) ) {
    strErr = label + ' that you have entered cannot be accepted!';
  }  
  
  // return error
  return strErr;
}

function validateEmailAddress(el,label) {
  var strErr = '';
  var strInput = trimAll(el.value);
  var objRegExp = /^([a-z0-9])+(.([a-z0-9])+)*@([a-z0-9]+\.{1})+[a-z0-9]{2,}$/i;

  // check for empty string
  if (strInput.length < 1)
    strErr = 'Please provide us your ' + label;
  else {
    // validate the email address
    if (objRegExp.test(strInput)) ;
      // do nothing for valid address
    else
      // construct error message
      strErr =  label + ' that you have provided is not valid!';
  }
    
  // return error
  return strErr;
}

function validateContactNumbers(mobile) {
  var strErr = '';
  var strMobile = trimAll(mobile.value);
  var alphaRE = /[a-zA-Z]+/;
  var mobileRE = /[\d$]{10,}/;
  
  // Check for empty contact number entry
  if (strMobile.length < 1) {
    strErr = 'Please provide us with a contact number';
  }
  
  // Validate each contact number
  else {  
    // Mobile Phone
    if (strErr.length < 1 && strMobile.length > 0) {
      if ( alphaRE.test(strMobile) ) {
        strErr = 'Mobile Phone that you have provided is not valid!';
      }
      else if ( !(mobileRE.test(strMobile)) ) {
        strErr = 'Mobile Phone that you have provided too short';
      }
    }
  } // end of validate each contact number
  
  return strErr;
}

function validateTextArea(el,label) {
  var strErr = '';
  var strInput = trimAll(el.value);
 
  // check for null value
  if (strInput == null) {
    strErr =  label + ' cannot be null!';
  }
  // check for empty string
  else if (strInput.length < 1) {
    // do nothing
  }
  // check for embedded script tag
  else if ( ( strInput.indexOf("<") != -1 ) || ( strInput.indexOf(">") != -1 ) ) {
    strErr = label + ' that you have entered cannot be accepted!';
  }  
  
  // return error
  return strErr;
}

// Check for anything was selected for the radio buttons
function validateRadioButton(eList, label) {
  var strErr = '';
  var n = 0;
  
  // Loop thru the radio buttons
  for(var i=0; i < eList.length; i++) {
    if (eList[i].checked)
      n++;
  }
  
  // Construct the error message
  if (n == 0) {
    strErr = 'Please select an option for your ' + label; + '!';
  }
  
  // return error message
  return strErr;
}

// validate Work Times drop down boxes
function validateWorkTimes(appDoc) {
  var strErr = '';
  var strID = '';
  var strValue, intFrom, intTo;
  var boolValid = new Boolean(false);
  
  document.getElementById("divAvailabilityStatus").style.backgroundColor = "#EAEAEA";
  /* check for all 'N/A' drop down values */
  for (var i=1; i < 15; i++) {
    strID = 'Select' + i;
    strValue = document.getElementById(strID).value;

    if (strValue!= 'none') {
      boolValid = true;
      break;
    } /* if statement */
  } /* for-loop */

  // construct error message
  if (boolValid == false)
  {
    strErr = 'Please provide us with correct details of your availability for work!';
    document.getElementById("divAvailabilityStatus").style.backgroundColor = "yellow";
  }
  /* END of check for all 'N/A' drop down values */

 for (var i=1; i < 15; i++) {
    strID = 'Select' + i;
    document.getElementById(strID).style.backgroundColor = "white";
 } /* for-loop */

  /* validate individual day */
  /* validate Monday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select1").selectedIndex);
    intTo   = parseInt(document.getElementById("Select8").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Monday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Monday';
      boolValid = false;
    }
    if (boolValid == false)
    {
	document.getElementById("Select1").style.backgroundColor = "yellow";
	document.getElementById("Select8").style.backgroundColor = "yellow";
    }
    
  }  /* END of validate Monday */
    
  /* validate Tuesday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select2").selectedIndex);
    intTo   = parseInt(document.getElementById("Select9").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Tuesday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Tuesday';
      boolValid = false;
    }
    
    if (boolValid == false)
    {
	document.getElementById("Select2").style.backgroundColor = "yellow";
	document.getElementById("Select9").style.backgroundColor = "yellow";
    }
  }  /* END of validate Tuesday */

  /* validate Wednesday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select3").selectedIndex);
    intTo   = parseInt(document.getElementById("Select10").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Wednesday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Wednesday';
      boolValid = false;
    }
    
    if (boolValid == false)
    {
	document.getElementById("Select3").style.backgroundColor = "yellow";
	document.getElementById("Select10").style.backgroundColor = "yellow";
    }
  }  /* END of validate Wednesday */

  /* validate Thursday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select4").selectedIndex);
    intTo   = parseInt(document.getElementById("Select11").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Thursday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Thursday';
      boolValid = false;
    }
    if (boolValid == false)
    {
	document.getElementById("Select4").style.backgroundColor = "yellow";
	document.getElementById("Select11").style.backgroundColor = "yellow";
    }
  }  /* END of validate Thursday */

  /* validate Friday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select5").selectedIndex);
    intTo   = parseInt(document.getElementById("Select12").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Friday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Friday';
      boolValid = false;
    }
    if (boolValid == false)
    {
	document.getElementById("Select5").style.backgroundColor = "yellow";
	document.getElementById("Select12").style.backgroundColor = "yellow";
    }
  }  /* END of validate Friday */

  /* validate Saturday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select6").selectedIndex);
    intTo   = parseInt(document.getElementById("Select13").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Saturday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Saturday';
      boolValid = false;
    }
    
    if (boolValid == false)
    {
	document.getElementById("Select6").style.backgroundColor = "yellow";
	document.getElementById("Select13").style.backgroundColor = "yellow";
    }
  }  /* END of validate Saturday */

  /* validate Sunday */
  if (boolValid && (strErr.length < 1)) {
    intFrom = parseInt(document.getElementById("Select7").selectedIndex);
    intTo   = parseInt(document.getElementById("Select14").selectedIndex);
    
    // 'From' cannot be 'N/A' when 'To' is not
    if ((intFrom == 0) && (intTo != 0)) {
      // construct error message
      strErr = 'Please advise us your preferred start time for Sunday';
      boolValid = false;
    }
    // 'From' cannot be >= 'To'
    else if ((intFrom != 0) && (intTo != 0) && (intFrom >= intTo)) {
      // construct error message
      strErr = 'Please advise us your preferred working times for Sunday';
      boolValid = false;
    }
    
    if (boolValid == false)
    {
	document.getElementById("Select7").style.backgroundColor = "yellow";
	document.getElementById("Select14").style.backgroundColor = "yellow";
    }
  }  /* END of validate Sunday */
  /* END of validate individual day */  
  return strErr;
}

// Enable the working hours timetable
function enableWorkTimes(appDoc) {
  var boolValue = false;
  
  // Enable individual working hours drop down boxes
  appDoc.getElementById("Select1").disabled = boolValue;
  appDoc.getElementById("Select2").disabled = boolValue;
  appDoc.getElementById("Select3").disabled = boolValue;
  appDoc.getElementById("Select4").disabled = boolValue;
  appDoc.getElementById("Select5").disabled = boolValue;
  appDoc.getElementById("Select6").disabled = boolValue;
  appDoc.getElementById("Select7").disabled = boolValue;
  appDoc.getElementById("Select8").disabled = boolValue;
  appDoc.getElementById("Select9").disabled = boolValue;
  appDoc.getElementById("Select10").disabled = boolValue;
  appDoc.getElementById("Select11").disabled = boolValue;
  appDoc.getElementById("Select12").disabled = boolValue;
  appDoc.getElementById("Select13").disabled = boolValue;
  appDoc.getElementById("Select14").disabled = boolValue;
}

// Disable the working hours timetable
function disableWorkTimes(appDoc) {
  var boolValue = true;
  
  // Disable individual working hours drop down boxes
  appDoc.getElementById("Select1").disabled = boolValue;
  appDoc.getElementById("Select2").disabled = boolValue;
  appDoc.getElementById("Select3").disabled = boolValue;
  appDoc.getElementById("Select4").disabled = boolValue;
  appDoc.getElementById("Select5").disabled = boolValue;
  appDoc.getElementById("Select6").disabled = boolValue;
  appDoc.getElementById("Select7").disabled = boolValue;
  appDoc.getElementById("Select8").disabled = boolValue;
  appDoc.getElementById("Select9").disabled = boolValue;
  appDoc.getElementById("Select10").disabled = boolValue;
  appDoc.getElementById("Select11").disabled = boolValue;
  appDoc.getElementById("Select12").disabled = boolValue;
  appDoc.getElementById("Select13").disabled = boolValue;
  appDoc.getElementById("Select14").disabled = boolValue;

  // Disable 'Apply To All' button
  appDoc.getElementById("ApplyToAll").disabled = boolValue;
}

var awAllOptionClick = function(e) {
  disableWorkTimes(document);
}

$E.addListener("awAll", "click", awAllOptionClick);

var awSelectedOptionClick = function(e) {
  enableWorkTimes(document);
}

$E.addListener("awSelected", "click", awSelectedOptionClick);

var awMonOnChange = function(e) {
  var intFromMon = parseInt(document.getElementById("Select1").selectedIndex);
  var intToMon = parseInt(document.getElementById("Select8").selectedIndex);

  // Disable 'Apply To All' button when either 'From' or 'To' value is N/A
  if (intFromMon == 0 || intToMon == 0) {
    document.getElementById("ApplyToAll").disabled = true;  
  }
  
  // Disable 'Apply To All' button when the 'From' greater or equals 'To' value
  else if ( (intFromMon != 0) && (intToMon != 0)
    && (intFromMon >= intToMon) ) {
    document.getElementById("ApplyToAll").disabled = true;
  }

  // Enable 'Apply To All' button
  else    
    document.getElementById("ApplyToAll").disabled = false;
}

$E.addListener(["Select1", "Select8"], "change", awMonOnChange );

var btnApplyToAllClick = function(e) {
  var strFromMon = document.getElementById("Select1").value;
  var strToMon = document.getElementById("Select8").value;

  if ( (strFromMon != 'none') && (strToMon != 'none') ) {
    // Update all the 'From' times
    document.getElementById("Select2").value = strFromMon;
    document.getElementById("Select3").value = strFromMon;
    document.getElementById("Select4").value = strFromMon;
    document.getElementById("Select5").value = strFromMon;
    document.getElementById("Select6").value = strFromMon;
    document.getElementById("Select7").value = strFromMon;    
    
    // Update all the 'To' times
    document.getElementById("Select9").value = strToMon;
    document.getElementById("Select10").value = strToMon;
    document.getElementById("Select11").value = strToMon;
    document.getElementById("Select12").value = strToMon;
    document.getElementById("Select13").value = strToMon;
    document.getElementById("Select14").value = strToMon;
  }
}

$E.addListener("ApplyToAll", "click", btnApplyToAllClick );

var hoursLimitOptionClick = function(e) {
  // hours drop down disabled?
  if (document.getElementById("HoursWorkWanted").disabled) 
    // enable hours drop down
    document.getElementById("HoursWorkWanted").disabled = false;

  // days drop down disabled?
  if (document.getElementById("DaysWorkWanted").disabled)
    // enable days drop down
    document.getElementById("DaysWorkWanted").disabled = false;  
}

$E.addListener(["HrsLimitMin", "HrsLimitMax"], "click", hoursLimitOptionClick);

var startReqOptionClick = function(e) {
  var optValue;
  var objElementList = document.getElementsByName("StartReq");

  for(var i=0; i < objElementList.length; i++) {
    if (objElementList[i].checked)
      optValue = objElementList[i].value;
  } /* for-loop */

  if ( optValue.toLowerCase() == 'immediately' ) {
    // clear Preferred Start Date text input
    document.getElementById("StartDate").value = "";
    
    // disable Preferred Start Date text input
    document.getElementById("StartDate").disabled = true;
    
    // close the calendar control
    $D.setStyle("calContainer", "display", "none");
  }
    
  else {
    // enable Preferred Start Date text input
    document.getElementById("StartDate").disabled = false;
    
    // display calendar control via focus method
    document.getElementById("StartDate").focus();
  } /* if-else */
}

$E.addListener(["StartImmediate","StartPref"], "click", startReqOptionClick );

function validateFile(el) {
  var fileName = trimAll(el.value);
  var strErr = '';
  var fileType;
  
  if (fileName.length < 1)
    strErr = 'Please provide us a copy of your resume!';
    
  else {
    if ( fileName.lastIndexOf(".") == -1 )
      strErr = 'The file that you have provided is not valid!';
    
    else {
      fileType = fileName.substr(fileName.lastIndexOf(".")+1, fileName.length);

      if (fileType.toLowerCase() != 'pdf')  {
        if (fileType.toLowerCase() != 'doc')  {
          if (fileType.toLowerCase() != 'docx')
            strErr = 'The file format that you have provided cannot be accepted!';
          }
      }
    }  
  }
    
  return strErr;
}

function validateResumeFile() {
  var retValue = true;
  var strErr = '';
  
  document.getElementById("ResumeFile").style.backgroundColor = 'white';
  strErr = validateFile(document.getElementById("ResumeFile"));
  
  if (strErr.length > 0) {
    alert(strErr);
    document.getElementById("ResumeFile").style.backgroundColor = 'yellow';
    retValue = false;
  }
  
  return retValue;
}

$E.addListener("ResumeFile", "change", validateResumeFile );

function validateSelectionList(eList) {
  var strErr = '';

  // check for empty selection list
  if ( eList.length < 1 )
    strErr = 'Please pick at least one preferred working location from our list of cafes';
  
  // since selection list is not empty
  else {  
    // loop thru them and mark them as selected for server submission
    for(var i=0; i < eList.length; i++) 
      eList.options[i].selected = true;
  }
  
  return strErr;
}

/* disable specific fields under 'Show Times' (Availability) tab */
function disableAvailability(appDoc) {
  var strErr = '';
  var optValue = '';
  var objElementList;
  
  /* Disable work times drop down boxes */
  objElementList = appDoc.getElementsByName("awStatus");
      
  // iterate thru for checked option
  for(var i=0; i < objElementList.length; i++) {
    if (objElementList[i].checked)
      optValue = objElementList[i].value;
  } /* for-loop */

  // conditions to disable the drop down boxes
  if ( optValue.length < 1 )
    disableWorkTimes(appDoc);    
  // 'all times' option selected
  else if ( optValue.toLowerCase() == 'all times' )
    disableWorkTimes(appDoc);


  /* Disable hours/days drop down boxes */
  strErr = validateRadioButton(appDoc.getElementsByName("HoursLimit"), 'working hours requirements');
  
  if (strErr.length > 0) {
    document.getElementById("HoursWorkWanted").disabled = true;
    document.getElementById("DaysWorkWanted").disabled = true;  
  } /* if statement */


  /* Disable Preferred Start Date text input */
  optValue = '';
  objElementList = appDoc.getElementsByName("StartReq");
      
  // iterate thru for checked option
  for(var i=0; i < objElementList.length; i++) {
    if (objElementList[i].checked)
      optValue = objElementList[i].value;
  } /* for-loop */

  // conditions to disable the drop down boxes
  if ( optValue.length < 1 )
    document.getElementById("StartDate").disabled = true;
  // 'immediately' option selected
  else if ( optValue.toLowerCase() == 'immediately' )
    document.getElementById("StartDate").disabled = true;
}
/******************************************************************************/
// validate fields under the 'Star Profile'(Personal Details) tab
function validatePersonalDetails(appDoc) {
  var retValue = true;
  var strErr = '';
  var objElement, optValue;
  
  // Validate applicant's name
  if (retValue && strErr.length < 1) { 
    strErr = validateTextInput(document.getElementById('FirstName'), 'First Name');
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      document.getElementById('FirstName').style.backgroundColor = 'yellow';
      alert(strErr);    
      retValue = false;
    }
    else
    {
	document.getElementById('FirstName').style.backgroundColor = 'white';
    }
  }
  
  if (retValue && strErr.length < 1) { 
    strErr = validateTextInput(document.getElementById('LastName'), 'Last Name');
    document.getElementById('LastName').style.backgroundColor = 'white';
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      alert(strErr);    
      retValue = false;
      document.getElementById('LastName').style.backgroundColor = 'yellow';
    }    
  } // End of Validate applicant's name

  // Validate applicant's email address
  if (retValue && strErr.length < 1) { 
    strErr = validateEmailAddress(document.getElementById('Email'), 'Email Address');
    
    document.getElementById('Email').style.backgroundColor = 'white';
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      alert(strErr);    
      retValue = false;
      document.getElementById('Email').style.backgroundColor = 'yellow';
    }
  } // End of Validate applicant's email address
  
  // Validate applicant's contact numbers
  if (retValue && strErr.length < 1) { 
    strErr = validateContactNumbers(document.getElementById('MobilePhone'));
    
    document.getElementById('MobilePhone').style.backgroundColor = 'white';
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      alert(strErr);
      retValue = false;
      document.getElementById('MobilePhone').style.backgroundColor = 'yellow';
    }
  } // End of Validate applicant's contact numbers

  // Validate applicant's working rights
  // Check whether the applicant selection
  if (retValue && strErr.length < 1) {
    strErr = validateRadioButton(document.getElementsByName("WorkingRights"), 'working rights');
    
    document.getElementById('WorkingRights').style.backgroundColor = "#EAEAEA";
    
    if (strErr.length > 0) {
      alert(strErr);
      retValue = false;
      document.getElementById('WorkingRights').style.backgroundColor = 'yellow';
    }
  }
  
  // Check for applicant's No selection
  if (retValue && strErr.length < 1) {
    objElement = document.getElementsByName("WorkingRights");

    for(var i=0; i < objElement.length; i++) {
      if (objElement[i].checked)
        optValue = objElement[i].value;
    }

    if ( optValue.toLowerCase() == 'no' ) {
      alert('Unfortunately, at present we are only able to offer positions to people that are legally entitled to work in Australia.\nIf your migration status changes, please feel free to reapply.');
      window.location = 'http://www.domecoffees.com/';     
    }
    
    if (strErr.length > 0) {
      alert(strErr);
      retValue = false;
    }
  }
  
  // End of Personal Details section
  return retValue;
}
/******************************************************************************/
// validate fields under the 'Show Times'(Availability) tab
function validateAvailability(appDoc) {
  var retValue = true;
  var strErr = '';
  var objElementList, optValue, strDate;
  
  // Validate applicant's work availability
  if (retValue && strErr.length < 1) {
    document.getElementById('divAvailabilityStatus').style.backgroundColor = "#EAEAEA";
    strErr = validateRadioButton(appDoc.getElementsByName("awStatus"), 'work availability');
    
    if (strErr.length > 0)
	document.getElementById('divAvailabilityStatus').style.backgroundColor = 'yellow';
    
    // Validate the drop down boxes for N/A values
    if (retValue && strErr.length < 1) {
      objElementList = appDoc.getElementsByName("awStatus");
      
      // iterate thru for checked option
      for(var i=0; i < objElementList.length; i++) {
        if (objElementList[i].checked)
          optValue = objElementList[i].value;
      } /* for-loop */
      
      // 'selected time' option selected
      if ( optValue.toLowerCase() == 'selected time' )
        strErr = validateWorkTimes(appDoc);
    }    

    if (strErr.length > 0) {
      alert(strErr);
      retValue = false;
    }  
  }
  // END of validate applicant's work availability
    
  // Validate applicant's working hours requirements
  if (retValue && strErr.length < 1) {
  
    document.getElementById('HoursWorkWanted').style.backgroundColor = 'white';
    document.getElementById('DaysWorkWanted').style.backgroundColor = 'white';	
    document.getElementById('HoursLimit').style.backgroundColor = "#EAEAEA";
  
  strErr = validateRadioButton(appDoc.getElementsByName("HoursLimit"), 'working hours requirements');
    
    if (strErr.length > 0)
	document.getElementById('HoursLimit').style.backgroundColor = 'yellow';
    
    // Validate the drop down boxes for zero values
    if (retValue && strErr.length < 1) {
      if ( (appDoc.getElementById("HoursWorkWanted").value == 0) && (appDoc.getElementById("DaysWorkWanted").value == 0) )
      {
        strErr = 'Please specify your working hours/days requirement!';
	document.getElementById('HoursWorkWanted').style.backgroundColor = 'yellow';
	document.getElementById('DaysWorkWanted').style.backgroundColor = 'yellow';	
      }
    }

    // Validate the drop down boxes for incorrect combination
    //if (retValue && strErr.length < 1) {
	//		var intHours = parseInt(appDoc.getElementById("HoursWorkWanted").selectedIndex);
	//		var intDays = parseInt(appDoc.getElementById("DaysWorkWanted").selectedIndex);
	//		
	//		if(( intHours > 0 ) && ( intDays > 0))
	//			strErr = 'Please specify either your working hours or days requirement';
   // }				
    
    if (strErr.length > 0) {
      alert(strErr);
      retValue = false;
    }
  } // END of validate applicant's working hours requirements

  // Validate applicant's Starting Date requirements
  if (retValue && strErr.length < 1) {
    
    document.getElementById('StartDate').style.backgroundColor = 'white';
    document.getElementById('StartReq').style.backgroundColor = "#EAEAEA";
    
    strErr = validateRadioButton(appDoc.getElementsByName("StartReq"), 'starting date requirements');
    
    if (strErr.length > 0)
	document.getElementById('StartReq').style.backgroundColor = 'yellow';
    
    // Validate StartDate text input field
    if (retValue && strErr.length < 1) {
      objElementList = appDoc.getElementsByName("StartReq");
      
      for(var i=0; i < objElementList.length; i++) {
        if (objElementList[i].checked)
          optValue = objElementList[i].value;
      } /* for-loop */
      
      // 'Preferred Start Date' option selected
      if ( optValue.toLowerCase() != 'immediately' ) {
        // validate Preferred Start Date text input        
        strDate = trimAll(appDoc.getElementById("StartDate").value);
        
        // check for empty string
        if ( strDate.length < 1 )
	{
          strErr = 'Please specify your preferred start date!'
	  document.getElementById('StartDate').style.backgroundColor = 'yellow';
	}
      }              
    } /* if */  
          
    if (strErr.length > 0) {
      alert(strErr);
      retValue = false;
    }
  } // END of validate applicant's Starting Date requirements

  
  // Validate applicant's selection of perferred working locations
  if (retValue && strErr.length < 1) {
    strErr = validateSelectionList(appDoc.getElementById("selectedLocations"));
    document.getElementById('selectedLocations').style.backgroundColor = 'white';
    
    if (strErr.length > 0) {
      alert(strErr);
      document.getElementById('selectedLocations').style.backgroundColor = 'yellow';
      retValue = false;
    }
  } // END of validate applicant's selection of perferred working locations
  
  return retValue;
}

// validate fields under the 'Character Notes'(AboutYou) tab
function validateAboutYou(appDoc) {
  var retValue = true;
  var strErr = '';
  
  // Validate applicant's Self Description
  if (retValue && strErr.length < 1) { 
    
    document.getElementById('selfDescription').style.backgroundColor = 'white';
    strErr = validateTextArea(appDoc.getElementById("selfDescription"), "Self Description");
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {    
      // display error message
      document.getElementById('selfDescription').style.backgroundColor = 'yellow';
      alert(strErr);    
      retValue = false;
    }
  } // End of Validate applicant's Self Description

  // Validate applicant's Talents and Interests
  if (retValue && strErr.length < 1) { 
    
    document.getElementById('talentsAndInterests').style.backgroundColor = 'white';
    strErr = validateTextArea(appDoc.getElementById('talentsAndInterests'), 'Talents And Interests');
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      alert(strErr);    
      document.getElementById('talentsAndInterests').style.backgroundColor = 'yellow';
      retValue = false;
    }
  } // End of Validate applicant's Talents and Interests
  
  // Validate applicant's goal sentence
  if (retValue && strErr.length < 1) { 
    
    document.getElementById('iHaveAGoalTo').style.backgroundColor = 'white';
    strErr = validateTextArea(appDoc.getElementById('iHaveAGoalTo'), 'Goal Sentence');
    
    // Check error msg returned from the method call above
    if (strErr.length > 0) {
      // display error message
      alert(strErr);    
      document.getElementById('iHaveAGoalTo').style.backgroundColor = 'yellow';
      retValue = false;
    }
  } // End of Validate applicant's goal sentence  
  
  // Validate applicant's resume filename
  if (retValue && strErr.length < 1) {
    
    document.getElementById('ResumeFile').style.backgroundColor = 'white';
    strErr = validateFile(appDoc.getElementById("ResumeFile"));
  
    if (strErr.length > 0) {
      alert(strErr);
      document.getElementById('ResumeFile').style.backgroundColor = 'yellow';
      retValue = false;
    }
  } // End of Validate applicant's resume filename
  
  return retValue;
}

function addNewOption(lsSelect, strText, strValue) {
  var objOption = new Option(strText, strValue);
  var selectLen = lsSelect.length;
  var boolNew = new Boolean(true);
  
  // add to a empty selection list
  if ( selectLen == 0 )
    lsSelect.options[selectLen] = objOption;

  // add to a populated selection list
  else if ( selectLen > 0 ) {
    
    // check against selection list for duplicate option
    for(var i=0; i < selectLen; i++) {
      if ( lsSelect.options[i].value == objOption.value ) {
        boolNew = false;
        break;
      }       
    }
    
    // add new option to selection list
    if (boolNew)
      lsSelect.options[selectLen] = objOption;
  }
}

var btnAddLocationClick = function(e) {
  var optionList = document.getElementById("CafeLocations");
  var selection = document.getElementById("selectedLocations");

  for(var i=0; i < optionList.length; i++) {
    if ( optionList.options[i].selected )
    {
      if (selection.length < 3)
	  addNewOption(selection, optionList.options[i].text, optionList.options[i].value);
      else
      {
	  alert("Please select a maximum of 3 locations."); 
	  break;
      }
    }
  }
}

$E.addListener("btnAddLocation", "click", btnAddLocationClick);

var btnResetSelectionClick = function(e) {
  var selection = document.getElementById("selectedLocations");
  var selectLen = selection.length;
  
  if ( selectLen > 0 ) {
    for(var i=selectLen-1; i > -1; i--)
      selection.options[i] = null;
  }
}

$E.addListener("btnResetSelection", "click", btnResetSelectionClick);


/* Calendar control specific client side functions */
// event handler for StartDate text input's focus event
function displayCalPanel(ev) {
  // retrieve text input position
  var tar = $E.getTarget(ev);
  var xy = $D.getXY(tar);
  xy[1] = xy[1] + 20;
  
  // align the calendar control below the text input
  $D.setStyle("calContainer", "position", "absolute");
  $D.setStyle("calContainer", "top", xy[1]+"px");
  $D.setStyle("calContainer", "left", xy[0]+"px");
  
  // specify the calendar control CSS style
  $D.setStyle("calContainer", "display", "block");
  $D.setStyle("calContainer", "width", "180px");  


  // setup the calendar control properties
  // set the mindate to be tomorrow's date
  var currentDate = new Date();
  var nextDay = new Date(currentDate.getTime() + 86400000);
  
  // finally, create the calendar control
	YAHOO.calendarControl = new YAHOO.widget.Calendar("calendarControl", "calContainer",
	                                                  { mindate: nextDay });
	YAHOO.calendarControl.selectEvent.subscribe(selectDateHandler, YAHOO.calendarControl, true);
	YAHOO.calendarControl.render();
}

$E.addListener("StartDate", "focus", displayCalPanel);

// event handler for calendar control's date select event
function selectDateHandler(type,args,obj) {
  var date = args[0][0];
  // update text input with the user selected date
  if ( date.length = 3 )
    document.getElementById("StartDate").value = date[2] + '/' + date[1] + '/' + date[0];
    
  $D.setStyle("calContainer", "display", "none");
}


/* StartDate's blur event overrides calendar control's selectDateHandler event
function hideCalPanel(ev) {
  $D.setStyle("calContainer", "display", "none");
}
$E.addListener("StartDate", "blur", hideCalPanel);
*/

