// check whether the textField is with empty value
function isEmpty(fieldName) {
	if ((fieldName == null) || (fieldName.length == 0)) {
		return true;
	}
	else {	return false;	}
}

function checkEmail(str) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(str)){ return true; }
	return false;
}

/* emergency e-mail validator which allows apostrophes */
function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >= 0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_&'";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}
/* emergency e-mail validator which allows apostrophes */


function popupURL(url,winWidth,winHeight,resizable,scrollbars) {
	if(winWidth == null){winWidth = '500';}
	if(winHeight == null){winHeight = '600';}
	if(resizable == null){resizable = 'yes';}
	if(scrollbars == null){scrollbars = 'yes';}
	myWindow=window.open(url,'popup','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + scrollbars + ',resizable=' + resizable + ',copyhistory=yes,width=' + winWidth + ',height=' + winHeight);
	myWindow.focus();
}

function checkDates(f)	{
	var daysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	var day   = f.day.value;
	var month = f.month.value;
	var year  = f.year.value;

	if ((year % 4) == 0 || (year % 400) == 0)	// leap year
		daysInMonth[1]++;
	if (day > daysInMonth[month - 1] || month > 12 || day > 31  || isNaN(day) || isNaN(month) || isNaN(year) || day.length == 0 || month.length == 0 || year.length == 0  ) {
		return true;
	}
	return false;
// Include the following parameters when checking for a birthdate || year > 2002 || year < 1880
}

/*
Function Name:	doCount
Description:	Requires 3 inputs. Counts the number of words in a form textarea.
*/
function doCount(formField, formFieldWordCounter, wordLimit)	{
	var wordArray = formField.value.split(/\s+/g);	// split on spaces to put words into an array, thus getting number of words
	formFieldWordCounter.value = wordLimit - wordArray.length;
	var warningName = formField.name + "WordWarning";

	if(wordArray.length > wordLimit)	{			// word limit exceeded
		document.getElementById(warningName).style.visibility = "visible";	// display warning message
	}
	else{
		document.getElementById(warningName).style.visibility = "hidden";	// hide warning message
	}
}


/* 
	Navigation amongst the results (and away to refine search) is done by form submission to allow
	the criteria that has been entered to be passed around (ie: maintain state).
	
	Haran Jan 2005: orderColumnSearchResults() - see function after navigateSearchResults() - submits form sorting by column

*/
function navigateSearchResults(formName, actionPage, startRow){
	// Set the startRow variable in the form
	if(startRow){
		document[formName].startRow.value = startRow;
	}	
	
	submitForm(formName, actionPage);
}

function orderColumnSearchResults(formName, actionPage, sortColumn){
	// Set the sortColumn variable in the form (and reset startRow to 1)
	if(sortColumn){
		document[formName].sortColumn.value = sortColumn;
		document[formName].startRow.value = 1;
	}	
	
	submitForm(formName, actionPage);
}

function orderNewsArchiveSearchResults(formName, actionPage, sortColumn){
	// Set the sortColumn variable in the form (and reset startRow to 1)
	if(sortColumn){
		document[formName].sortByDate.value = sortColumn;
		document[formName].startRow.value = 1;
	}	
	
	submitForm(formName, actionPage);
}

function submitForm(formName, actionPage){
	// Adjust the action page
	if(actionPage){
		document[formName].action = actionPage;
	}
	document[formName].submit();
}

function populateSelectBox(selectBoxObj,optionsValueArray,optionsIdArray){
	selectBoxObj.length = optionsValueArray.length;
	for(var i=0; i < optionsValueArray.length; i++){
		selectBoxObj.options[i] = new Option(optionsValueArray[i],optionsIdArray[i]);
	}
}

function setSelectBoxDefault(selectBoxObj,defaultArray){
	//alert(selectBoxObj + ', ' + defaultArray);
	//Loop over the array of selected items
	for(var i = 0; i < defaultArray.length; i++){
		var thisSelection = defaultArray[i];
		//alert('thisSelection = ' + thisSelection);
		//Loop over all items in the list and see if any value matches thisSelection
		for(var j = 0; j < selectBoxObj.length; j++){
			if(selectBoxObj.options[j].value == thisSelection){
				selectBoxObj.options[j].selected = true;
				break;
			}
		}
	}
}

/* toggles the display property of a particular object in the page */
function toggleDisplay(objectId) {
	if ( objectId.style.display == 'none' ){
		objectId.style.display = 'block';
	} else {
		objectId.style.display = 'none';
	}
}

function toggleSectionVisibility(sectionName){
	// toggle the visibility of the html content
	toggleDisplay(document.getElementById(sectionName));
}


// Used in the job search section to save the search criteria to a psa
function saveJobSearch(formName, actionPage){
	submitForm(formName, actionPage);
}
function leftTrim(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	return sString;
}
// added by A Livie to do string trims
function trim(sString){
	while (sString.substring(0,1) == ' '){
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' '){
		sString = sString.substring(0,sString.length-1);
	}
return sString;
}
// added by A Livie to do textarea counter
function textCounter(field, countfield, maxlimit) {
if (field.value.length > maxlimit) // if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter
else 
countfield.value = maxlimit - field.value.length;
}

function toggleLayer(whichLayer)
{
if (document.getElementById)
{
// this is the way the standards work
var style2 = document.getElementById(whichLayer).style;
style2.display = style2.display? "":"block";
}
else if (document.all)
{
// this is the way old msie versions work
var style2 = document.all[whichLayer].style;
style2.display = style2.display? "":"block";
}
else if (document.layers)
{
// this is the way nn4 works
var style2 = document.layers[whichLayer].style;
style2.display = style2.display? "":"block";
}
}

function OpenNewWindow_OnClick( url, width, height )
{
    var _PageName = url;
	var _Width    = width;
	var _Height   = height;
	var _WndName  = 'Wnd';

	var scrWidth  = screen.width;
	var scrHeight = screen.height;

	var topLeft_X = Math.round( ( scrWidth  - _Width  ) / 2 );
	var topLeft_Y = Math.round( ( scrHeight - _Height ) / 2 );

	var features  = 'toolbar=0,' 	  +
			        'scrollbars=1,' +
			        'location=0,'   +
			        'status=0,'  +
			        'menubar=0,'    +
			        'resizable=0,'  +
			        'width='  + _Width    + ','   +
			        'height=' + _Height   + ','   +
			        'left='   + topLeft_X + ','   +
			        'top='    + topLeft_Y + '';

	window.open( _PageName, _WndName, features );
}

function isValidURL(s) {
	if (s.indexOf("@") >= 0) return false
	var re = /^(http(s?)\:\/\/)?(([0-9a-zA-Z\-]+\.)+)([a-zA-Z]{2,})(\/.*)*?(\?.*)?$/i
	return (re.test(s))
}

/* CODE FOR ITEM-3524 CONVERT JS CODE TO EVENT HANDLERS */
 $(document).ready(function() {
 	
	/* FUNCTION ONCLICK recruiter's office (homepage - OK button Recruiter sign in)
	 * substitution onclick="if (validateLogin(document.adminLogin) == true) document.adminLogin.submit(); return false;" 
	 ************************************/	
 	$("div.inputFloatSubmit a#recruiterSignInOKbtn").click(function () { 
		if (validateLogin(document.adminLogin) == true) 
			document.adminLogin.submit(); 
			return false;
    });		

 	/* FUCTION ONCLICK OPEN recruiter's office (Password reminder link)
 	 * substitution href="javascript:popupURL('http://#request.siteURL#/admin/forgottenPassword.cfm','530','450');
	************************************/
	$("a[rel='recruiterReminderPass']").click(function () {
  		    var features = "width=530, height=450";
  		    newwindow=window.open(this.href, 'eFC', features);
  		    return false;
		});	

 	/* FUCTIONS ONCLICK OPEN recruiter's office (Homepage - Menu Items href)
 	 * substitution href="javascript:doGoToLink('#menuArrayOption#_#qGetResumesOptions.currentRow#', '#qGetResumesOptions.URL#');"
	************************************/
	$("a.companySpecific").click(function () {
		/*var ArrayRow = $(this).parent().prev().text();
		var URL = $(this).parent().children('div').text();*/		
		var data = $(this).siblings("dl"), arrayRow = data.find("[title=arrayRow]").text(), URL = data.find("[title=URL]").text();
		doGoToLink(arrayRow,URL);
		return false;
	})	

 	/* FUCTION ONCLICK OPEN recruiter's office (Menu Items – Help Pop-Up)
 	 * substitution onclick="window.open('faq.cfm?id=#qGetJobsOptions.FAQId#','helpWindow','scrollbars=yes,resizable=no,width=400,height=300');"
	************************************/
	$("a[rel='help_Pop-Up']").click(function () {
	    var features = "scrollbars=yes,resizable=no,width=400,height=300";
	    newwindow=window.open(this.href, 'eFC', features);
	    return false;
	});	
	
 	/* FUCTION ONCLICK OPEN recruiter's office (Menu Item – OFCCP)
 	 * substitution onclick="window.open('http://#request.partnerVars.staticHostName#/assets/pdf/admin/ofccptext.pdf','helpWindow','scrollbars=yes,resizable=no,width=800,height=600');"
	************************************/
	$("a[rel='OFCCP_Pop-Up']").click(function () {
	    var features = "scrollbars=yes,resizable=no,width=800,height=600";
	    newwindow=window.open(this.href, 'eFC', features);
	    return false;
	});	

 	/* FUCTION ONKEYUP  recruiter's office (input textbox Search)
 	 * substitution onkeypress="if(window.event && window.event.keyCode == 13) {showTheSearchResult();return false;}"
	************************************/
	$("div#backOfficeContentContainer input[name='companySearchString']").keypress(function () {
		if(window.event && window.event.keyCode == 13) {
			showTheSearchResult();
			return false;
		}
	});	

 	/* FUCTION ONCLICK  recruiter's office (input button Search)
 	 * substitution onclick="showTheSearchResult();return false;"
	************************************/
	$("div#backOfficeContentContainer input[name='companySearchSubmitBtn']").click(function () {
		showTheSearchResult();
		return false;
	});	

 	/* FUCTION ONKEYUP  recruiter's office (input textbox Siebel Ref Search)
 	 * substitution onkeypress="if(window.event && window.event.keyCode == 13) {showTheSiebelSearchResult();return false;}"
	************************************/
	$("div#backOfficeContentContainer input[name='SiebelSearchString']").keypress(function () {
		if(window.event && window.event.keyCode == 13) {
			showTheSiebelSearchResult();
			return false;
		}
	});	
	
 	/* FUCTION ONCLICK  recruiter's office (input button Siebel Ref Search)
 	 * substitution onclick="showTheSiebelSearchResult();return false;"
	************************************/
	$("div#backOfficeContentContainer input[name='SiebelSearchSubmitBtn']").click(function () {
		showTheSiebelSearchResult();
		return false;
	});	
	
 	/* FUCTIONS ONCLICK recruiter's office (Every SubSections - SubNav Items href)
 	 * substitution href="javascript:doGoToLink('#selectMenu#_#s#', '#jsstringformat(request.adminMenuArray[selectMenu][3][s][2])#')"
	************************************/
	$("a.submenu").click(function () {
		var data = $(this).parents('li').next('li.subnavVariables'), arrayRow = data.find("[title=arrayRow]").text(), URL = data.find("[title=URL]").text();
		doGoToLink(arrayRow,URL);
		return false;
	});
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - grid title items to order by - links)
 	 * substitution href="javascript:doOrderBy('...')"
	************************************/
	$("a.doOrderBy").click(function () {
		var data = $(this).attr("rel");
		doOrderBy(data);
		return false;
	});	
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user link)
 	 * substitution href="javascript:doGoToPage('#request.encryptionObj.encryptString(loginref)#')"
	************************************/
	$("td.companyUserListTableRow a").click(function () {
		var data = $(this).siblings("a.LoginRefEO").find("[title=EOloginRef]").text(); //find semantic information
		doGoToPage(data);
		return false;
	});	
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - “Buy Job ads” Button)
 	 * substitution onClick="javascript: location.href='<cfif getEmployer.preBuyCredits EQ 1>http://#request.siteURL#/admin/jobSlotPreBuy.cfm?employerRef=#getEmployer.employerRef#<cfelse>#webstoreUrl#</cfif>'"
	************************************/
	$("div#buyMoreButton").click(function () {
		var data = $(this).siblings("div").find("[title=urlBuyJobAds]").text();
		url = data.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		window.location.replace(url);
		return false;
	});	
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - “Post a New Job” link)
 	 * substitution href="javascript:alert('#JSStringFormat("#application.phrase[request.translationId][1699]#")#.')"
 	 * 				href="javascript:alert('#JSStringFormat("#application.phrase[request.translationId][1700]#")#.')"
	************************************/
	$("a#postANewJob").click(function () {
		var data = $(this).siblings("a").find("[title=textAlertPostMoreJobs]").text();
		alert(data);
		return false;
	});	
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - every “Job Title” item link)
 	 * substitution href="javascript:<cfif locationDependant NEQ "">document.jobListFrm.locationSpecific.value=#locationDependant#; </cfif>doGoToJobDetail('#jobRef#', 'Edit', '#Evaluate("#request.qListJobs#.loginRef")#');"
	************************************/
	$("td.jobListTableRow a.[title=View Job Details]").click(function () {
		var data = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobListFrmLocationSpecific]").text();
		var jobRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobRef]").text();
		var loginRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=loginRef]").text();
		var locationDependant = $(this).parents("td").siblings("td.jobListTableData").find("[title=locationDependant]").text();
		loginRef = loginRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		jobRef = jobRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		if (data.lenght > 0) { 
			document.jobListFrm.locationSpecific.value = locationDependant;
			}
		doGoToJobDetail(jobRef, 'Edit', loginRef);
		return false;
	});	

 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - every “Apps” number link for each “Job Title”)
 	 * substitution href="javascript:doGoToJobAppList('#jobRef#', '#Evaluate("#request.qListJobs#.loginRef")#');"
	************************************/
	$("td.jobListTableRow a.[title=View Applications]").click(function () {
		var jobRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobRef]").text();
		var loginRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=loginRef]").text();
		loginRef = loginRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		jobRef = jobRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		doGoToJobAppList(jobRef, loginRef);
		return false;
	});
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - status Radio Buttons YES)
 	 * substitution beginActivateJob(this, '#jobRef#', this.form.action, '#locationCountryID#', '#singleSubSectorId#', '#employerJobCreditsID#', '#variables.localDateFormatObj.getLocalDateFormat(dDateToFormat=jobSlotExpiryDate,sLanguage=request.language,partnerRegion=request.partnerRegion)#', '#jobCreditsRegionID#', '#jobCreditsCountryID#')"
	************************************/	
	$("input.jobListActiveYES").click(function () {
		var jobRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobRef]").text();
		var actionForm = $(this).parents("td").siblings("td.jobListTableData").find("[title=actionForm]").text();
		var locationCountryId = $(this).parents("td").siblings("td.jobListTableData").find("[title=locationCountryId]").text();
		var singleSubSectorId = $(this).parents("td").siblings("td.jobListTableData").find("[title=singleSubSectorId]").text();
		var employerJobCreditsID = $(this).parents("td").siblings("td.jobListTableData").find("[title=employerJobCreditsID]").text();
		var localDate = $(this).parents("td").siblings("td.jobListTableData").find("[title=localDate]").text();
		var jobCreditsRegionID = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobCreditsRegionID]").text();
		var jobCreditsCountryID = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobCreditsCountryID]").text();
		
		/*console.log("This: ", this);
		console.log("JobRef: ", jobRef);
		console.log("Action Form: ", eval(actionForm));
		console.log("Location Country ID: ", locationCountryId);
		console.log("Single SubSector ID: ", singleSubSectorId);
		console.log("Employer Job Credits ID: ", employerJobCreditsID);
		console.log("Local Date: ", localDate);
		console.log("Job Credits Region ID: ", jobCreditsRegionID);
		console.log("Job Credits Country ID: ", jobCreditsCountryID);
		console.log(this,jobRef,actionForm,locationCountryId,singleSubSectorId,employerJobCreditsID,localDate,jobCreditsRegionID,jobCreditsCountryID);*/
		
		beginActivateJob(this,jobRef,eval(actionForm),locationCountryId,singleSubSectorId,employerJobCreditsID,localDate,jobCreditsRegionID,jobCreditsCountryID);		
	});

 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - status Radio Buttons NO)
 	 * substitution onclick="doToggleActive(this, '#jobRef#',#request.frmName#,'#locationDependant#');"
	************************************/	
	$("input.jobListActiveNO").click(function () {
		var jobRef = $(this).parents("td").siblings("td.jobListTableData").find("[title=jobRef]").text();
		var formName = $(this).parents("td").siblings("td.jobListTableData").find("[title=formName]").text();
		var formName = $('body').find('[name='+formName+']');
		var locationDependant = $(this).parents("td").siblings("td.jobListTableData").find("[title=locationDependant]").text();
		
		/*console.log("This: ", this);
		console.log("JobRef: ", jobRef);
		console.log("Form Name: ", formName);
		console.log("Location Dependant: ", locationDependant);*/

		doToggleActive(this,jobRef,formName[0],locationDependant);
	});
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - link Check All)
 	 * substitution onclick="check(document.#request.frmName#.boolRenewList,'tickBox')"
	************************************/
	$("td.jobListTableHeader a#tickBox").click(function () {
		var formName = $(this).parents("td").siblings("td.jobListTableData").find("[title=formName]").text();
		var docRenewList = $("form[name=" + formName + "] input[name=boolRenewList]");
		/*console.log("FormName: ", formName);
		console.log("docRenewList: ", docRenewList);*/
		check(docRenewList,'tickBox');
		return false;
	});
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - every copy link for each “Job Title)
 	 * substitution ="javascript: doGoToJobDetail('#jobRef#', 'PostAsNew', '#loginRef#')"
	************************************/
	$("a.JobListTableCopy").click(function () {
		var jobRef = $(this).parents("td").siblings("td.JobListTableCopyData").find("[title=jobRef]").text();
		var loginRef = $(this).parents("td").siblings("td.JobListTableCopyData").find("[title=loginRef]").text();
		loginRef = loginRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		jobRef = jobRef.replace(/^\s*|\s*$/g,''); // Get rid off blank spaces on IE
		doGoToJobDetail(jobRef,'PostAsNew',loginRef);
		return false;
	});
	
 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - Delete button)
 	 * substitution onclick="if(!confirm('#deleteMessage#')) { return false }"
	************************************/
	$("input.[name=deleteSingleJobsBtn]").click(function () {
		var deleteMessage = $(this).parents("td").siblings("td.JobListTableDeleteBtn").find("[title=deleteMessage]").text();
		var deleteMessage2 = deleteMessage.replace(/\\n/g, "\n"); //Transform \n to a br
		if(!confirm(deleteMessage2)) { return false } else { return true } // If true send form
	});

 	/* FUCTIONS ONCLICK recruiter's office (Jobs - BackOffice user detail - popup buttons)
 	 * substitution onclick="cancelActivate();" - onclick="submitJobForActivation();" - onclick="cancelActivate();"
	************************************/
	$("div#okButtonBox input.[name=ok], div#commitButtonBox input.commitBtnLive").click(function () {
		cancelActivate();
	});
	$("div#commitButtonBox input.commitBtnJobLive").click(function () {
		submitJobForActivation();
		return false;
	});

  });