//Global variables for cross browser detection and other variables
//********* NOTE: Still need to sort out compatibility with Mozilla **********//
var blnMac = (navigator.userAgent.toLowerCase().indexOf("mac") != -1) ? true : false;			
var blnNS4 = (document.layers) ? true : false;
var blnNS6 = (!document.all && document.getElementById) ? true : false;
var blnIE4 = (document.all && !document.getElementById) ? true : false;
var blnIE5 = (document.all && document.getElementById) ? true : false;

var emailRE = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var intCount = 0;				
//***************Other Browser detection features**********************************//
//Browser detection stuff - Used this way because cant use object detection as opera and IE have same compatible objects and cant be
//tested
var appVersion = navigator.userAgent.toLowerCase();
var is_opera = (appVersion.indexOf("opera") != -1 || appVersion.indexOf("opera") != -1);
var is_firefox = (appVersion.indexOf("firefox") != -1 || appVersion.indexOf("firefox") != -1);
var is_mozilla = (appVersion.indexOf("gecko") != -1 && appVersion.indexOf("firefox") == -1);
var is_safari = (appVersion.indexOf("safari") != -1);

//Browser dependent document. calls
function ftnSetObjString(strObjItem) {
	if(blnNS4) return "document.layers('" + strObjItem + "')";
	if(blnIE4) return "document.all." + strObjItem;
	if(blnIE5 || blnNS6) {
		if(blnMac && blnIE5) {
			return "document.all['" + strObjItem + "']";
		} else {
			return "document.getElementById('" + strObjItem + "')";	
		}
	}	
}

/***************************************************************
Name: ftnGetObjItem
Input parameters: 
      strObjItem - The name of the element you are controlling
Function objective:
      Cross browser document.all calls
***************************************************************/
function ftnGetObjItem(strObjItem) {
	return eval(ftnSetObjString(strObjItem));
}

/***************************************************************
Name: Controsl the creation and reading of cookies
Input parameters: 
      strName - name of cookie e.g. username
      strValue - value of the item e.g. yippanion
      dteExpires - Not used at moment, but if you want the cookie
      to be removed earlier, you can place a date here.
Function objective:
      Cross browser document.all calls
***************************************************************/
//Function to create a cookie for the login details
function ftnCreateCookie(strName,strValue, dteExpires)
{
	var date = new Date();
	date.setTime(date.getTime()+(dteExpires*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	
	document.cookie = strName + "=" + strValue + expires + "; path=/";
}

//Function to read the cookie
function readCookie(strName)
{
	var nameEQ = strName + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

/***************************************************************
Name: ftnCheckMandatory()
Input parameters: 
      strValue - value of the textfield or textarea
Function objective:
      To check for empty strings
***************************************************************/
function ftnCheckMandatory(strValue) {
   if(strvalue) { return true; } 
   else { return false; }	
}

/***************************************************************
Name: calendarPicker()
Input parameters: 
      strField - Name of the textfield
      objField - The actual textfield object
Function objective:
      Function for the asp.net calendar popup
***************************************************************/
function calendarPicker(strField, objField) {
	ftnGetObjItem(strField).value = '';
	window.open('/library/includes/calendarPicker.aspx?field=' + objField + '&strDate=' + ftnGetObjItem(strField).value,'calendarPopup','width=230,height=171,resizable=no,location=no');
}	

//========================== Open new Window Section ========================================

// Diverts the popup's parent to the supplied URL
function divert_parent(URL) {
	window.location.href = URL;	
}

// Sends the form (of id formPopup) submission to the a window of supplied height/width
function popupForm(W, H)
{	
		window.open('', 'test', 'height=' + H + ',width=' + W + ',scrollbars=1');
		document.formPopup.target='test';
		document.formPopup.submit();
		
		return false;			
}

// Generates a popup of supplied Height, Width that shows the supplied URL
function popupWin(URL, W, H)
{
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=" + W + ",height=" + H + "');");	
}

//=========================== DHTML DIV Stuff ===============================================
/***************************************************************
Name: ftnOpenDIV
Input parameters: 
      objItem - The object or element dealing with
      intPopupYPos - Setting the y position of the DIV
      blnUseBlankBg - Show blank bg or not(true/false)
Function objective:
      To open oe show DIVs that are hidden. usually used for the
      popup windows
***************************************************************/
function ftnOpenDIV(objItem, intPopupYPos, blnUseBlankBg) {
	ftnGetObjItem(objItem).style.display = 'block';	
	if(blnUseBlankBg == true) {
	   //ftnSetBlankBg(true);
	}	
}

/***************************************************************
Name: ftnCloseDIV
Input parameters: 
      objItem - The object or element dealing with
      intPage - May not be used now
      blnUseBlankBg - Show blank bg or not(true/false)
Function objective:
      To close or hide DIVs that are hidden. usually used for the
      popup windows
***************************************************************/
function ftnCloseDIV(objItem, intPage, blnUseBlankBg) {
	ftnGetObjItem(objItem).style.display = 'none';	
	if(blnUseBlankBg == true) {	
	   //ftnSetBlankBg(false);													
	}
}				

/***************************************************************
Name: ftnSetBlankBg
Input parameters: 
      blnSetBg - Either shows the BG when you choose true else
                 false will hide the BG
Function objective:
      This is for the BG image that is used in conjunction with
      the popup windows so that the user cannot press anywhere
      else on he screen
***************************************************************/
function ftnSetBlankBg(blnSetBg) {  
   if(blnSetBg == true) {
      ftnGetObjItem('blankDIV').style.display = 'block';
	   if(is_opera) {
	      ftnGetObjItem('blankDIV').innerHTML = '<img src="/images/bg_transblue.png" border="0" height="' + document.body.clientHeight + '" width="' + document.body.clientWidth + '" />';
	   } else {
	      ftnGetObjItem('blankDIV').innerHTML = '<img src="/images/bg_transblue.gif" border="0" height="' + document.body.clientHeight + '" width="' + document.body.clientWidth + '" style="opacity: .9; filter:alpha(opacity=90); -moz-opacity:0.9; khtml-opacity: .90;" />';	   
	   }
   } else {
      ftnGetObjItem('blankDIV').style.display = 'none';
   }   	
}

//========================== Dropdown Disabling stuff =======================================

/***************************************************************
Name: ftnDisableEnableDropdowns
Input parameters: NONE
Function objective:
      Disables all dropdowns throughout the page
***************************************************************/
function ftnDisableEnableDropdowns() {
   var ddl = document.getElementsByTagName('select');
	for(var x=0; x<ddl.length; x++) {
	   if(ddl.item(x).disabled == false) {
	      ddl.item(x).disabled=true;
	      ddl.item(x).style.visibility='hidden';
	   } else {
	      ddl.item(x).disabled=false;
	      ddl.item(x).style.visibility='visible';
	   }	   
	}
}

//=========================== Msg Box Stuff =================================================

function ftnShowWaitDIV() {
	var strLine = '...';

	if(intCount < strLine.length+1) {
		ftnGetObjItem('msgDIV').style.display = 'block';
		document.getElementById('msgDIV').innerHTML = '<span style="color:#CE011E;font-size:5em"><b>Please Wait ' + strLine.substring(0, intCount) + '</b></span>';
		intCount++;
	} else {
		intCount = 0;
	}	
	
	setTimeout('ftnShowWaitDIV()', 180);
}

//============================== Get position of object =======================================

/***************************************************************
Name: ftnFindPosY
Input parameters: 
      obj - The object to the get the position of
Function objective:
      gets the Y position of the object
***************************************************************/
function ftnFindPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

/***************************************************************
Name: ftnFindPosX
Input parameters: 
      obj - The object to the get the position of
Function objective:
      gets the X position of the object
***************************************************************/
function ftnFindPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

//============================ Validation =====================================================

/***************************************************************
Name: ftnCheckDate
Input parameters: 
      strDate - The date passed in as a string e.g. 12-09-2004
Function objective:
      Validates the date field
***************************************************************/
function ftnCheckDate(strDate) {
	var regExpDate = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/;
	
	if(strDate.length > 0) {
		if(regExpDate.test(strDate) == false) {
			return false;
		} else {
			if(strDate.substring(6, 10) < 1900 || strDate.substring(6, 10) > 2049) {
				return false;
			} else {
				return true;
			}
		}
	}
}

/***************************************************************
Name: ftnCheckIsNumeric
Input parameters: 
      strNumber - The number passed in as a string e.g. 12
Function objective:
      Validates the numeric field
***************************************************************/
function ftnCheckIsNumeric(strNumber) {
	var validNumbers = /(^-?\d\d*$)/;
	
	if(validNumbers.test(strNumber) == false) {
		return false;
	} else {
		return true;
	}
}

/***************************************************************
Name: ftnCheckEmail
Input parameters: 
      strEmail - The email passed in as a string e.g. ayip@milkround.com
Function objective:
      Validates the email field
***************************************************************/
function ftnCheckEmail(strEmail) {
	if(emailRE.test(strEmail) == false) {
		return false;
	} else {
		return true;
	}
}

/***************************************************************
Name: ftnNoEnter
Input parameters: 
      strEmail - None
Function objective:
      Disables submit using enter key
***************************************************************/
function ftnNoEnter(e) {
	var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
	if (key == 13) {
		return false;
	}
}

/***************************************************************/

//========================== Combo Box Stuff ==================================================

/***************************************************************
Name: Combo Box Function (Overall Name)
Input parameters: 
      strURL - The URL of the processing ASP page to process the
               results
      strCompanyLetters - The string passed in for the process 
               to take place
      intExecOnLetterPos - Executes the script after a certain
               number of characters have been pressed
Function objective:
      This is the control for the Combo Box stuff
***************************************************************/

//NOTE: Will need to place ftnShowDropdowns and ftnHideDropdowns on actual pages if they have other dropdowns on the exsiting pages.
//This will be used until a better solution is found.
function PrepareRequestXML(strURL, strCompanyLetters, intExecOnLetterPos, objID, objDDLID, objYPos, objXPos) {		
   //Executed on the number of letters the user has typed.
   if(document.getElementById('tmpLoadDIV')) {
		document.getElementById('tmpLoadDIV').style.display = 'block';
   }   
   if(intExecOnLetterPos) {
      if(strCompanyLetters.length >= intExecOnLetterPos) {      
         GetRequestXML(strURL, strCompanyLetters, objID, objDDLID, objYPos, objXPos);					
      } else if(strCompanyLetters.length == 0) {      
         GetRequestXML(strURL, strCompanyLetters, objID, objDDLID, objYPos, objXPos);	
      }
   } else {
      GetRequestXML(strURL, strCompanyLetters, objID, objDDLID, objYPos, objXPos);	
   }	   
}

function GetRequestXML(url,strCompanyChars, objIDPassed, objDDLIDPassed, objYPosPassed, objXPosPassed) {				
	url += "&strComp=" + strCompanyChars;	
	
	//Set new position of the dropdown list
	ftnGetObjItem('lst_' + objDDLIDPassed).style.top = (objYPosPassed-243) + 'px';
	//ftnGetObjItem('lst_' + objDDLIDPassed).style.left = (objXPosPassed-232) + 'px';
	
	//Set new position of Not in List div filtered for each browser
	//NOTE:NOT USED AT MOMENT, IF EVERYTHING OK THEN GOOD TO DELETE
	/*
	if(is_firefox || is_mozilla) {
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.top = (objYPosPassed-936) + 'px';
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.left = (objXPosPassed-463) + 'px';
	} else if(is_opera) {
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.top = (objYPosPassed-880) + 'px';
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.left = (objXPosPassed-458) + 'px';
	} else {
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.top = (objYPosPassed-852) + 'px';
		ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.left = (objXPosPassed-462) + 'px';
	}		
	*/
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
		xmlhttp = false;
		}
	}
	@end @*/
	
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {				
	xmlhttp = new XMLHttpRequest();
	}

	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState!=4 ){						
				//
			}else{	
				//If nothing is matched, show not in list												
				if(xmlhttp.responseText.length == 17 && ftnGetObjItem(objIDPassed).value.length > 0) {
					ftnGetObjItem('lst_' + objDDLIDPassed).innerHTML = '';	
					if(document.getElementById('tmpLoadDIV')) {
						ftnGetObjItem('tmpLoadDIV').style.display = 'none';									
					}
					ftnGetObjItem('lst_' + objDDLIDPassed).style.display = 'block';
					ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.display = 'block';	
					ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.backgroundColor = '#FFFFFF';	
				//If nothing is typed or searched
				} else if(xmlhttp.responseText.length == 17 || ftnGetObjItem(objIDPassed).value.length == 0) {				
					ftnGetObjItem('lst_' + objDDLIDPassed).style.display = 'none';	
					ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.display = 'none';	
					if(document.getElementById('tmpLoadDIV')) {	
						ftnGetObjItem('tmpLoadDIV').style.display = 'none';		
					}
			   //Otherwise, show the results in the dropdown
				} else {						   						
					if(document.getElementById('tmpLoadDIV')) {					
						ftnGetObjItem('tmpLoadDIV').style.display = 'none';						
					}
					ftnGetObjItem('lst_' + objDDLIDPassed).innerHTML = xmlhttp.responseText;	
					if(document.getElementById('tblCompany')) {
		            var tbl = document.getElementById('tblCompany');
		            var td = tbl.getElementsByTagName('td');			            
	            } else {
		            var tbl = '';
		            var td = '';
	            }
	            
	            //Gets the longest string and stores it into the maxstring variable for use with setting the width of the dropdown
	            var intMaxString = 0;	            
	            for(x=0; x<td.length;x++) {			
	               if(ftnGetObjItem('anchor' + x + '').innerHTML.length > intMaxString) {
	                  intMaxString = ftnGetObjItem('anchor' + x + '').innerHTML.length;			               
			         } 	
		         }	     
		         //Calculates whether the string is actually longer than the textfield. If it is, then re-sizes the DIV		         
		         if(intMaxString * 6 > 342) {
		            ftnGetObjItem('lst_' + objDDLIDPassed).style.width = intMaxString * 6;	
		            ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.width = intMaxString * 6;                
		         } else {
		            ftnGetObjItem('lst_' + objDDLIDPassed).style.width = '342';
		            ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.width = '342';
		         }	         					
					ftnGetObjItem('lst_' + objDDLIDPassed).style.display = 'block';	
					ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.display = 'block';	
					ftnGetObjItem('lst_' + objDDLIDPassed + '_notinlist').style.backgroundColor = '#FFFFFF';					
				}															
			}
		};
	try {
		xmlhttp.send(null);
	}
	catch(e) {
		alert(e.description);
	}
}

//Function that selects text that is highlighted
function ftnGetSelection() {
	var txt = '';
	var foundIn = '';
	if (window.getSelection) {
		txt = window.getSelection();
	}
	else if (document.getSelection) {
		txt = document.getSelection();
	}
	else if (document.selection) {
		txt = document.selection.createRange().text;
	}
	else return;

	alert(txt);
}	

//TODO: Going opposite way needs to pressed twice beofre the next selection is highlighted
var currentCell = 0;	//Counter for the highlighting of items
var evtKeyup = '';	//Variable to store the javascript code. Text string doesnt work with it
		
function ftnChangeBGColor(objCell, strColour) {
	ftnGetObjItem(objCell).style.backgroundColor = strColour;
}	

//NOT USED AT MOMENT
function ftnCloseCompanyList() {
	ftnGetObjItem('lst_companies').style.display='none';
}

//Function to get the current style of the object or element
function ftnGetStyle(el) {
	if(el.currentStyle) {
		return el.currentStyle.backgroundColor;
	} else if(document.defaultView) {
		return document.defaultView.getComputedStyle(el, '').getPropertyValue("background-color");
	} else {
		return "Don\'t know how to get color";
	}
}		

//Function that controls the whole key pressed by user
function ftnKeyPressed(e, objID, objHiddenID, objHiddenCurrID) {
	var key = e.keyCode;

	if(document.getElementById('tblCompany')) {
		var tbl = document.getElementById('tblCompany');
		var td = tbl.getElementsByTagName('td');	
	} else {
	   var tbl = '';
		var td = '';
	}
			
	//Reset counter to 0 when a new search takes place
	if(key != 38 && key != 40) {
		if(evtKeyup == '') {
			evtKeyup = ftnGetObjItem(objID).onkeyup;
		}
		ftnGetObjItem(objID).onkeyup = evtKeyup;
		currentCell = 0;
	}
		
	//Controls the down arrow key - NOTE:63233 is keyCode for MAC ??!!!
	if((key == 40 || key == 63233) && currentCell < td.length) {			
		if(is_opera || is_firefox || is_mozilla || is_safari) {
			ftnGetObjItem(objID).onkeyup = '';
		}
		td.item(currentCell).className = 'grey';
		
		if(currentCell != 0) {
			td.item(currentCell-1).className = 'white';
		} 
		
		//Controls the down scrolling of the DIV so that we dont lose sight of the highlighted object
		if(currentCell >= 6 && currentCell < td.length-1) {
			ftnGetObjItem('lst_' + objHiddenID).scrollTop = ftnGetObjItem('lst_' + objHiddenID).scrollTop + 20;
		}
		
		//This will not increment when we are at the last item as there is no more items to follow
		if(currentCell < td.length-1) {
			currentCell++;
		}
	}	
		
	//Controls the up arrow key
	if((key == 38 || key == 63232) && currentCell > 0) {	
		td.item(currentCell-1).className = 'grey';			
		if(currentCell != td.length) {
			td.item(currentCell).className = 'white';
		}
			
		//Controls the up scrolling of the DIV so that we dont lose sight of the highlighted object
		if(currentCell <= td.length-6 && currentCell > 0) {
			ftnGetObjItem('lst_' + objHiddenID).scrollTop = ftnGetObjItem('lst_' + objHiddenID).scrollTop - 20;
		}
		
		//This will not decrement when we are at the first item as there is no more items before this
		if(currentCell > 1) {
			currentCell--;
		}
	}	
		
	//Controls the enter key and sets the input text box to the value that is set to grey / highlighted
	if(key == 13) {		    	
		for(x=0; x<td.length;x++) {			
			if(td.item(x).className == 'grey') {
			   if(ftnGetObjItem('anchor' + x + '').innerHTML.indexOf('--&gt;') != -1) {
			      ftnGetObjItem(objID).value = ftnGetObjItem('anchor' + x + '').innerHTML.substring(ftnGetObjItem('anchor' + x + '').innerHTML.indexOf('--&gt;')+7,ftnGetObjItem('anchor' + x + '').innerHTML.length).replace('&amp;', '&');
			      //This is for the hidden value that is sent to the function to add details for different sections.
			      if(objHiddenCurrID) {
			         ftnGetObjItem(objHiddenCurrID).value = ftnGetObjItem('id' + x).value;			         
			      } else {
			         ftnGetObjItem(objHiddenID).value = ftnGetObjItem('id' + x).value;
			      }			     
			   } else {			      
			      ftnGetObjItem(objID).value = ftnGetObjItem('anchor' + x + '').innerHTML.replace('&amp;', '&');
			      //This is for the hidden value that is sent to the function to add details for different sections.
			      if(objHiddenCurrID) {
			         ftnGetObjItem(objHiddenCurrID).value = ftnGetObjItem('id' + x).value;		
			      } else {
			         ftnGetObjItem(objHiddenID).value = ftnGetObjItem('id' + x).value;
			      }
			   }				
				ftnGetObjItem(objID).blur();		
				ftnGetObjItem('lst_' + objHiddenID).style.display='none';	
				ftnGetObjItem('lst_' + objHiddenID + '_notinlist').style.display = 'none';		
				ftnShowDropdowns();						
			} 	
		}	
	}	
	
	//Controls the Escape key
	if(key == 61) {
		ftnGetObjItem('lst_' + objHiddenID).style.display='none';	
	}		
}	

//Handles the click on the Not in List link from dropdown
function ftnNotInList() {
	ftnGetObjItem('lst_employers').style.display = 'none';
//	ftnGetObjItem('txtemployers').value = '';
	ftnGetObjItem('currentemp').value = '';
	ftnGetObjItem('lst_employers_notinlist').style.display = 'none';
	
	if(ftnGetObjItem('lbl_otheremp')) {
		ftnGetObjItem('lbl_otheremp').style.display = 'inline';
		ftnGetObjItem('txt_otheremp').style.display = 'inline';
		ftnGetObjItem('divOtheremp').style.padding = '10px 0 0 0';
	}	
}

//NOTE: Code that is used for the comboList box
function ftnHideDropdowns() {
	//Hide existing dropdowsn as DIV always behind them				
}

function ftnShowDropdowns() {
	//Unhide existing dropdowsn as DIV always behind them				
}							

/***************************************************************
Name: ftnMenuRollOver
Input parameters: 
      objField - The actual object to change on rollover
Function objective:
      Changes attributes of a given object
***************************************************************/
function ftnMenuRollOver(objField) {		
	objField.style.backgroundColor='#A8A8A8';
}

/***************************************************************
Name: ftnMenuRollOut
Input parameters: 
      objField - The actual object to change on rollout
Function objective:
      Changes attributes of a given object
***************************************************************/
function ftnMenuRollOut(objField) {		
	objField.style.backgroundColor='#FFFFFF';
}

function preloadImages() {
	var d=document; 
	if(d.images) { 
		if(!d.p) d.p=new Array();
			var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
			if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];
		}
	}
}

function ftnFilterJobRole(ranges, intLocID) {
	selectedIndex = 0;
	var dropDown = ftnGetObjItem('lst_jobroles');

	if(dropDown) {
		dropDown.length = 0;
		
		if(ranges) {
			dropDown.disabled = false;
			for(index=0; index<ranges.length; index++) {
				var arrItem = ranges[index].split('|');
				dropDown[index] = new Option(arrItem[1],arrItem[0]);				
			}
			dropDown.options[selectedIndex].selected = true;
		} else {
			dropDown.disabled = true;
		}
	}
}

function ftnFilterJobRoleAdmin(ranges, intLocID) {
	selectedIndex = 0;
	var dropDown = ftnGetObjItem('ddlJobroles');

	if(dropDown) {
		dropDown.length = 0;
		
		if(ranges) {
			dropDown.disabled = false;
			for(index=0; index<ranges.length; index++) {
				var arrItem = ranges[index].split('|');
				dropDown[index] = new Option(arrItem[1],arrItem[0]);				
			}
			dropDown.options[selectedIndex].selected = true;
		} else {
			dropDown.disabled = true;
		}
	}
}

function ftnFilterPrefJobRoleAdmin(ranges, intLocID) {
	selectedIndex = 0;
	var dropDown = ftnGetObjItem('ddlPrefJobroles');

	if(dropDown) {
		dropDown.length = 0;
		
		if(ranges) {
			dropDown.disabled = false;
			for(index=0; index<ranges.length; index++) {
				var arrItem = ranges[index].split('|');
				dropDown[index] = new Option(arrItem[1],arrItem[0]);				
			}
			dropDown.options[selectedIndex].selected = true;
		} else {
			dropDown.disabled = true;
		}
	}
}

/***************************************************************
Name: Javascript Ordering Section
Input parameters: 
      NONE
Function objective:
      Re-order table columns without refreshing the page
***************************************************************/

var SORT_COLUMN_INDEX;

function sortables_init() {
	// Find all tables with class sortable and make them sortable
	if (!document.getElementsByTagName) return;
	tbls = document.getElementsByTagName("table");
	for (ti=0;ti<tbls.length;ti++) {
		thisTbl = tbls[ti];
		if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
				//initTable(thisTbl.id);
				ts_makeSortable(thisTbl);
		}
	}
}

function ts_makeSortable(table) {
	if (table.rows && table.rows.length > 0) {
		var firstRow = table.rows[0];
	}
	if (!firstRow) return;
	   
	// We have a first row: assume it's the header, and make its contents clickable links
	for (var i=0;i<firstRow.cells.length;i++) {
		var cell = firstRow.cells[i];
		var txt = ts_getInnerText(cell);
		cell.innerHTML = '<a href="#" class="sortheader" onclick="ts_resortTable(this);return false;">'+txt+'<span class="sortarrow">&nbsp;</span></a>';
	}
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk) {
	// get the span
	var span;
	for (var ci=0;ci<lnk.childNodes.length;ci++) {
		if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
	}
	var spantext = ts_getInnerText(span);
	var td = lnk.parentNode;
	var column = td.cellIndex;
	var table = getParent(td,'TABLE');
	   
	// Work out a type for the column
	if (table.rows.length <= 1) return;
	var itm = ts_getInnerText(table.rows[1].cells[column]);
	sortfn = ts_sort_caseinsensitive;
	if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
	if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
	if (itm.match(/^[£$]/)) sortfn = ts_sort_currency;
	if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
	SORT_COLUMN_INDEX = column;
	var firstRow = new Array();
	var newRows = new Array();
	for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
	for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

	newRows.sort(sortfn);

	if (span.getAttribute("sortdir") == 'down') {
		ARROW = '&nbsp;&nbsp;&uarr;';
		newRows.reverse();
		span.setAttribute('sortdir','up');
	} else {
		ARROW = '&nbsp;&nbsp;&darr;';
		span.setAttribute('sortdir','down');
	}
	   
	// We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
	// don't do sortbottom rows
	for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
	// do sortbottom rows only
	for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}
	   
	// Delete any other arrows there may be showing
	var allspans = document.getElementsByTagName("span");
	for (var ci=0;ci<allspans.length;ci++) {
		if (allspans[ci].className == 'sortarrow') {
				if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
					allspans[ci].innerHTML = '&nbsp;&nbsp;&nbsp;';
				}
		}
	}
	      
	span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
	// y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
	if (aa.length == 10) {
		dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
	} else {
		yr = aa.substr(6,2);
		if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
		dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
	}
	if (bb.length == 10) {
		dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
	} else {
		yr = bb.substr(6,2);
		if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
		dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
	}
	if (dt1==dt2) return 0;
	if (dt1<dt2) return -1;
	return 1;
}

function ts_sort_currency(a,b) { 
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
	return parseFloat(aa) - parseFloat(bb);
}

function ts_sort_numeric(a,b) { 
	aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
	if (isNaN(aa)) aa = 0;
	bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX])); 
	if (isNaN(bb)) bb = 0;
	return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
	if (aa==bb) return 0;
	if (aa<bb) return -1;
	return 1;
}

function ts_sort_default(a,b) {
	aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
	bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
	if (aa==bb) return 0;
	if (aa<bb) return -1;
	return 1;
}


function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
	if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent){
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be removed");
	}
} 

function ftnParseSalary(txtSalary, blnMinSalary) 
{
	var oMatches;
	
	// Safari hack.
	if(navigator.userAgent.toLowerCase().indexOf("safari",0) > -1) {	
		// Remove the pound sign from the RegEx 
		// if the script is executed in a Safari browser.
		oMatches = txtSalary.match(/(\s*\d+[,|\s]?\d*\.?\d*k?)/gi);
	} else {
		oMatches = txtSalary.match(/(\£?\s*\d+[,|\s]?\d*\.?\d*k?)/gi);
	}
		
	//var oMatches = txtSalary.match(/(\£?\s*\d+[,|\s]?\d*\.?\d*k?)/gi);
	//var oMatches = txtSalary.match(/(£?\s*\d+[,|\s]?\d*\.?\d*k?)/gi);

    if(blnMinSalary == true) {
        if (oMatches == null) return 0;
    } else {
        if (oMatches == null) return '';
    }	

	// Ok, so oMatches contains all the numerical substrings that could possibly be a salary
	// with maybe an optional pound sign on the front, and an optional K at the end
	// We're try and work out the salary as follows:
	// If there are any matches beginning with £ then we'll use the biggest of these for the salary
	// this will hopefully catch things like '£10000 for the first 6 months + £50 expenses per month"
	// Else if there is more than one numerical match use the biggest value for the salary
	// this will hopefully catch things like 'c10000 for the first 6 months"
	// else if there is only one numerical match assume that is the salary 
	// else return NaN

	var bestMatch = -1;
	var bestMatchHasPound = false;
	var temp;

	var thisMatchHasPound;
	var hasTrailingK;

	for (var i = 0; i < oMatches.length; i++) {
		temp = oMatches[i];

		// begin by tidying the match up
		temp = temp.replace(" ", "");
		temp = temp.replace(",", "");
		temp = temp.toUpperCase();

		// does the potential salary have a pound sign?
		// if so remove it, and remember that it had one
		if (temp.substr(0, 1) == "£") {
			temp = temp.substr(1);
			thisMatchHasPound = true;
		}
		else {
			thisMatchHasPound = false;
		}

		// does ths potential salary have a trailing K?
		// if so remove it, and remember that it had one
		if (temp.substr(temp.length - 1) == "K") {
			temp.substr(0, temp.length - 1);
			hasTrailingK = true;
		}
		else {
			hasTrailingK = false;
		}

		temp = parseFloat(temp);
		if (!isNaN(temp)) {
			// if this match had a trailing K, convert it to thousands
			if (hasTrailingK) { temp = temp * 1000; }

			if (thisMatchHasPound) {
				if (bestMatchHasPound) {
					// Already have a match beginning with a pound sign
					// So this new match is only better if it's bigger
					if (temp > bestMatch) bestMatch = temp;
				}
				else {
					// No matches with a pound sign so far
					// So this is the best so far
					bestMatch = temp;
					bestMatchHasPound = true;
				}
			}
			else if (!bestMatchHasPound) {
				// Haven't found any pound matches so far, so this number is the best
				// match for a salary if it's the biggest
				if (temp > bestMatch) bestMatch = temp;
			}
		}
	}

	if (bestMatch < 0) {
	    if(blnMinSalary == true) {
	       	return 0;
	    } else {
	    	return '';
	    }	
	}

	// cutoff salaries at £10,000,000
	if (bestMatch > 9999999) { bestMatch = 9999999; }

	// round any pence figure to 2 decimal places
	// eg, 23.5 becomes 23.50 and 54.416 becomes 54.41

	bestMatch = bestMatch.toString();
	temp = bestMatch.indexOf(".");

	if (temp != -1) {
		if (bestMatch.length - temp == 2) { bestMatch += "0"; }
		if (bestMatch.length - temp > 3) { bestMatch = bestMatch.substr(0, temp + 3); }
	}

	return "" + bestMatch;
}

/***************************************************************
Name: unloading
Input parameters: 
      strObjItem - The name of the element you are controlling
Function objective:
      Cross browser document.all calls
***************************************************************/
function unloading (userId) {
		window.open('unload.aspx?userId=' + userId,'100','100');
}