// JavaScript Document

var debug = true; 

/***************************** GLOBAL PATHS : MUST UPDATE ****************************************/
var adInfoPath = '/sponsorads';//used to return info on a company during a rollover
var rdInfoPath = '/recruiterdirectory?rm=summary_popup';//used to return info on a company during a rollover
var adInfoPreviewPath = '/adm/sponsorads_preview';// used to preview sponsorads for administrators
/**************************************************************************************************/

var external_popup;
var externalCounted = 0;
var timer;

/***********************
* Class:BookmarkedJob
* stores a bookmarked Job
************************/
function BookmarkedJob(id) {
	this.jobID = id;
}

BookmarkedJob.prototype.toString = function() {
	return this.jobID;
}

BookmarkedJob.prototype.fromString = function(theString) {
	this.jobID = theString;	
}

/***************************
 * Class:SavedSettings
 * stores search parameters for
 * jobs search
 ****************************/
function SavedSettings(site) {
	//user settings
	this.help = false;
	this.largeFont = false;
	 
	//last search
	this.kw = ""//keyword
	this.ind = new Array();	//family
	this.occ = new Array();	//category
	this.wt = new Array();	//worktype
	this.cs = new Array();	//location
	this.rg = new Array();	//area
	this.sub = "";
	this.sur = 15000;			//surrounding suburbs
	this.sal = 0;				//low salary
	this.sah = 200000;		//hi salary
	this.dt = 30;				//date
	this.rname = "";			//recruiter name
	this.sor = 0;				//sorting
	this.CID = 0;				//clientid for recruiter/SME

	//set the base portion of our cookie names
	this.cookieBase = (site) ? site + '_' : '';
	
	//load in the values from our cookies
	this.loadSettings();
}
 
/********************
 * reads settings from cookies
 *********************/
SavedSettings.prototype.loadSettings = function() {
	var str = this.readCookie('help');			//help setting

	if (str == "true") {
		this.help = true;
	}
 
	str = this.readCookie('largeFont');		//font size setting
	if (str == "true") {
		this.largeFont = true;
	}

	str = this.readCookie('lastSearch');		//the last search the user did
	if (str!=null) {
		this.fromURLString(str);
	}

	// Locations on the Search page(or any page that requires) is open by default.
	this.locationSearchPage = 1;
	// View all / less on the Search page closed by default.
	this.locationViewAll = 0;
	this.IpodTermsClosed = 1;

}
 
/***********
 * saves cookies
 ************/
SavedSettings.prototype.saveSettings = function() {
	this.createCookie('help',this.help,365);
	this.createCookie('largeFont',this.largeFont,365);
	this.createCookie('lastSearch',this.toURLString(),365);
 
}
 
 /****************
 * cookie helpers
 *****************/
SavedSettings.prototype.createCookie = function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
		var expires = "";
	}
	document.cookie = this.cookieBase + name + "=" + escape(value) + expires + "; path=/";
}

SavedSettings.prototype.readCookie = function(name) {
	var nameEQ = this.cookieBase + name + "=";
	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 unescape(c.substring(nameEQ.length, c.length));
		}
	}
	return null;
}

SavedSettings.prototype.eraseCookie = function(name) {
	createCookie(this.cookieBase + name, "", -1);
}

 //returns an url string of search parameters
 SavedSettings.prototype.toURLString = function() {

//------------------------
// DJW 28/02/2007 added sub, sur, cid, etc.
//------------------------
 	var urlString = "ind=" + this.ind + "&kw="+ encodeURIComponent(this.kw) + "&sal=" + this.sal
 							+ "&sah=" +	this.sah + "&dt=" + this.dt + "&sor=" + this.sor
 							+ "&sub=" + this.sub + "&sur="+ this.sur+ "&CID=" + this.CID
							+ "&rname=" + encodeURIComponent(this.rname)
							;

	for(var i = 0;i<this.cs.length;i++) {
 		urlString += "&cs=" + this.cs[i];
	}

	for(var i = 0;i<this.wt.length;i++) {
 		urlString += "&wt=" + this.wt[i];
	}

	for(var i = 0;i<this.occ.length;i++) {
 		urlString += "&occ=" + this.occ[i];
	}

//------------------------
// DJW added 28/02/2007 rg, etc.
//------------------------
	for(var i = 0;i<this.rg.length;i++) {
 		urlString += "&rg=" + this.rg[i];
	}

	return urlString;

}
 
 /***********************************
 * parses a url search string for setting
 * and saves them.  Normally used with cookie
 * kw=&loc=&sal=80000&sah=200000&dt=30
 ************************************/
SavedSettings.prototype.fromURLString = function(theString) {
	params = theString.split('&');
	for(var i = 0;i< params.length;i++) {
		var str = params[i];
		var name = str.substring(0,str.indexOf('='));
		var value = str.substring(str.indexOf('=')+1,str.length);
		if (value != '') {
			switch(name) {
				case 'sal':	
					this.sal = value;
					break;

				case 'sah':	
					this.sah = value;
					break;

				case 'dt':	
					this.dt = value;
					break;

				case 'wt':	
					this.wt.push(value);
					break;
				case 'occ':	
					this.occ.push(value);
					break;

				case 'kw':	
					this.kw = decodeURIComponent(value);
					break;

				case 'rname':	
					this.rname = decodeURIComponent(value);
					break;

				case 'ind':	
					this.ind.push(value);
					break;

				case 'cs':
					this.cs.push(value);
					break;

				case 'sor':	
					this.sor = value;
					break;

				case 'sub':	
					this.sub = value;
					break;

				case 'sur':	
					this.sur = value;
					break;

				case 'CID':	
					this.CID = value;
					break;

				case 'rg':	
					this.rg.push(value);
					break;

				default:
					break;
			}
		}

	}
}

SavedSettings.prototype.getMember = function(name) {
	return this[name];
}

SavedSettings.prototype.setMember = function(name,value) {		
	this[name] = value;
}

/*******************************
*	Save the Tag cloud Industry (Job Category) and/or Occupation (sub Category)
*  into the lastSearch Cookie
********************************/
SavedSettings.prototype.saveTagCloudToCookie = function(industry, occupation) {
	this.ind = new Array();
	this.occ = new Array();

	if (industry) {
		this.ind.push(industry);
	}

	if (occupation) {
		this.occ.push(occupation);
	}

	//tell object to write cookies
	this.saveSettings();
}
 
/******** End SavedSettings **********/

/******** start main jjjApplication controller ********/

/*******************************
* Application constructor.
* created in onload on each page
* gets user cookies and sets values
* 
*******************************/
function JJJApplication(site) {
	this.savedSettings = new SavedSettings(site); //holds the saved settings object
	this.adRequest = null;
	this.helpVisible = false;//help div shown
	this.ajaxWait = null;
	
	//if help is enabled so set help text to hide
	if (this.savedSettings.getMember('help')) {
		this.enableHelp(true);
	}
	//if large font is enabled set it on
	if (this.savedSettings.getMember('largeFont')) {
		this.setFontSize(true);
	}
	if ($('dateLabel') != undefined){
		$('dateLabel').innerHTML = this.savedSettings.getMember('dt') + ' days';
		$('lowSalary').innerHTML = '$'+ this.savedSettings.getMember('sal');
		$('highSalary').innerHTML = '$'+ this.savedSettings.getMember('sah');
	}

	this.bookmarkedJobs = new Object();					//assocative array
	this.bookmarkCount = 0;

	this.viewedJobs = new Object();						//assocative array
	this.viewedCount = 0;
	
	this.selectedExternalApplicationOID = new Array();      // stores the IDs of external job applications that have been 
															// applied to via the new Apply Now icon on the results page.
	  
	this.blockedExternalApplicationOID = new Array();	// stores all the IDs of blocked external job applications.													

	this.loginPopuptimeout = null;						//login popup timeout
	this.fieldsUnderneathLoginPopuptimeout = null;  //login fix up fields underneath form timeout
	this.timeout = null;										//popup timeout
	this.popUpscope = null;									//pppup scope

	this.loadBookmarkedJobs();
	this.loadViewedJobs();

}

 /*****************************************
 * Removes a job from the cookie name passed,
 * displays an info box.
 *
 * e: event
 * cookieName: Name of cookie to update.
 * oid: OrderID
 *****************************************/
 JJJApplication.prototype.updateOIDcookie = function(e, cookieName, oid) {

	var targ;
	if (!e) {
		var e = window.event;
	}

	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}

	var el = $('infoBox');

	if(el != undefined) {
		el.parentNode.removeChild(el);
	}

	//create div and set attributes
	el = document.createElement('div');
	el.setAttribute('id','infoBox');
	el.style.zIndex = 1000;

	if (cookieName && oid) {

		el.innerHTML = '<br>Job removed from list';
		var saveString;

		switch (cookieName) {
			case 'viewed':
				this.viewedJobs[oid] = null;
				this.viewedCount--;
				saveString = this.viewedToString();
				this.savedSettings.createCookie('viewed', saveString);
				break;

			case 'bookmarked':
		 		this.bookmarkedJobs[oid] = null;
				this.bookmarkCount--;
				saveString = this.bookmarkToString();
				this.savedSettings.createCookie('bookmarked', saveString);
				break;

			default:
				el.innerHTML = 'Invalid cookie passed';
				break;
		}
	}

	//insert the div before all else in the DOM's body
	var parent = document.getElementsByTagName('body').item(0);
	parent.insertBefore(el,parent.firstChild);
	new Effect.Center('infoBox');

	//work out position of job we are removing and locate 'infoBox' there 
	var order = document.getElementById('oid_'+oid+'_'+oid);
	if (order) {
		var pos = findXY(order); // array [xpos, ypos]
		if (pos[1]) {
			el.style.top = pos[1] + 'px';
		}
	}
	
	new Effect.Fade('infoBox',{queue: 'end'});

}


 /*******************************************
 * Loads the bookmark cookie and selects the
 * approprate job checkboxes
 ********************************************/
JJJApplication.prototype.loadBookmarkedJobs = function() {
 	var savedString = this.savedSettings.readCookie('bookmarked');//read the cookie
 	
 	if(savedString != null) {
 		//if there is a cookie 

 		var arr = savedString.split(',');//split cookie string in to array
 		for(var i = 0;i < arr.length;i++) {
 			if(arr[i]!="") {
 				//if a value
 				this.bookmarkedJobs[arr[i]] = new BookmarkedJob(arr[i]);//create a new bookmark
 				this.bookmarkCount++;//increment count

 			}
 		}

 	  	this.selectBookmarkedJobs();
	}

 	if ($('bookmarkCount') != undefined) {
		if (this.bookmarkCount) {
	 		$('bookmarkCount').innerHTML = this.bookmarkCount;
		} else {
	 		$('bookmarkCount').innerHTML = "0";
		}
 	}
}
  
JJJApplication.prototype.selectBookmarkedJobs = function() {
	var forms = document.forms['jobs'] || document.forms['jobsForm'];
	if (forms) {
		for(bookmark in this.bookmarkedJobs) {
			var prefixes = ['OID_', 'JOTD_OID_', 'POPUP_OID_'];
			for (idx=0; idx<prefixes.length; idx++) {
				var job = prefixes[idx] + this.bookmarkedJobs[bookmark];
				//if the jobs are listed update selections
				if (forms[job]) {
					//if this job is on the page
					forms[job].checked = true; //check it
				}
			}
		}
	}
}
 
 /*****************************************
 * Adds or removes a job to our bookmarks memeber, displays an info
 * box with the count and higlights the 
 * selected jobs tool box
 *
 * e: event
 * id: job id
 *****************************************/
 JJJApplication.prototype.bookmarkJob = function(e,id,jotd) {

	var targ;
	if (!e) {
		var e = window.event;
	}

	if (e.target) {
		targ = e.target;
	} else if (e.srcElement) {
		targ = e.srcElement;
	}

	var el = $('infoBox');

	if(el != undefined) {
		el.parentNode.removeChild(el);
	}

	//create div and set attributes
	el = document.createElement('div');
	el.setAttribute('id','infoBox');
	el.style.zIndex = 1000;

	var text = '<br>';

	//add or removed if checked or not
	if(targ.checked) {
		this.bookmarkedJobs[id] = new BookmarkedJob(id);
		this.bookmarkCount++;
		text += 'Job<br>Bookmarked';
	} else {
		this.bookmarkedJobs[id] = null;
		this.bookmarkCount--;
		if (this.bookmarkCount < 0) {
			this.bookmarkCount = 0;
		}
		text += 'Bookmark<br>Removed';
	}
	
	//also update other check box if jotd and job on same page
	var other = (jotd) ? 'OID_'+id : 'JOTD_OID_'+id;
	if ($(other)) {
		$(other).checked = (targ.checked) ? true : false;
	}
	
	var saveString = this.bookmarkToString();
	
	this.savedSettings.createCookie('bookmarked',saveString);
	
	el.innerHTML = text;

	//insert the div before all else in the DOM's body
	var parent = document.getElementsByTagName('body').item(0);
	parent.insertBefore(el,parent.firstChild);
	new Effect.Center('infoBox');
	
	new Effect.Fade('infoBox',{queue: 'end'});
 	if ($('bookmarkCount') != undefined) {
		if (this.bookmarkCount) {
	 		$('bookmarkCount').innerHTML = this.bookmarkCount;
		} else {
	 		$('bookmarkCount').innerHTML = "0";
		}
	}
 	if ($('bookmarkHighlight') != undefined) {
		new Effect.Highlight('bookmarkHighlight',{startcolor:'#333333',queue: {scope: 'highlight',position: 'end'}});
	}
}

 /*********************************************
 * turns bookmarks in to a string
 * pass true for a url parameter string
 * else return a comma sepertated string
 *********************************************/
JJJApplication.prototype.bookmarkToString = function(url) {
	var theString = "";
 	for(bookmark in this.bookmarkedJobs) {
		if (this.bookmarkedJobs[bookmark] != null) {
			if(url) {
				//create a url paramString
				theString += "&OID="+this.bookmarkedJobs[bookmark].toString();
			} else {
				theString += this.bookmarkedJobs[bookmark].toString() + ",";
			}
		}
	}

	return theString;
}
 
 
 /*******************************************
 * Loads the viewed Jobs cookie
 ********************************************/
JJJApplication.prototype.loadViewedJobs = function() {
	var savedString = this.savedSettings.readCookie('viewed');		//read the cookie
	
	if(savedString != null) { 
		//if there is a cookie
		var arr = savedString.split(',');//split cookie string in to array
		for(var i = 0;i < arr.length;i++) {
			if (arr[i]!="") {
				//if a value
				this.viewedJobs[arr[i]] = new BookmarkedJob(arr[i]);//create a new bookmark
				this.viewedCount++;//increment count
					
			}
		}
		if($('viewedCount')!=undefined) {
		 	$('viewedCount').innerHTML = this.viewedCount;
		}
	}
}
  
/*****************************************
 * Adds or removes a job to our viewedJobs memeber
 *
 * id: job id
 *****************************************/
JJJApplication.prototype.viewJob = function(id) {
	
	this.viewedJobs[id] = new BookmarkedJob(id);
	
	var saveString = this.viewedToString();
	
	this.savedSettings.createCookie('viewed', saveString);
	
}
  
 /*********************************************
 * turns viewed jobs in to a string
 * pass true for a url parameter string
 * else return a comma seperated string
 *********************************************/
JJJApplication.prototype.viewedToString = function(url) {
	var theString = "";
	for(bookmark in this.viewedJobs) {
		if(this.viewedJobs[bookmark]!=null) {
			if(url) { //create a url paramString
				theString += "&OID="+this.viewedJobs[bookmark].toString();
			} else {
				theString += this.viewedJobs[bookmark].toString() + ",";
			}
		}
	}
	
	return theString;
}

/********************************
* turns on help system
* 
* pass true if you don't want to change
* current value. ie turning it after loading cookie
* changes the help tool help to 'hide text'
*********************************/
JJJApplication.prototype.enableHelp = function(noChange) {

	if(!noChange)//only swap settings if we want to
		this.savedSettings.help = !this.savedSettings.help;
		
	if(this.savedSettings.help)
	{
		$('helptool').setAttribute('help','Hide help');
		MM_swapImage('helpimg','','/images/tools/help_on.gif',1)
	}
	else
	{
		$('helptool').setAttribute('help','Show help');
		MM_swapImgRestore();
	}

	this.savedSettings.saveSettings();
}

/****************************
* displays the 'help' attribute
* in obj tag in a new div.
* pass event, obj with help, 
* overide to show help regardless if enabled
*
* modified 25/7/07 to use standard popup
*****************************/
JJJApplication.prototype.showHelp = function(event,obj,override)
{
	
	if((!this.helpVisible && this.savedSettings.help)||override){
		this.helpVisible = true;
		
		this.createPopup(event,obj.getAttribute('help'),Math.random(),true);
	
		/***** old code
		
		//create help div and set attributes
		var helpDiv = document.createElement('div');
		helpDiv.setAttribute('id','help' );
		helpDiv.className = 'help';
		helpDiv.style.display = "none";//hide it for effects
		
		setPos(event,helpDiv,{x:0,y:5});//set the position to the mouses
		
		helpDiv.innerHTML = obj.getAttribute('help');//add text from help attribute
		
		//insert the help before all else in the DOM's body
		var parent = document.getElementsByTagName('body').item(0);
		parent.insertBefore(helpDiv,parent.firstChild);
		Effect.Appear('help',{ duration: 0.5,to:0.85});//pretty effects
		*/
	}


}

//removes the help div if it is visible
// modified 25/7/07 to use standard popup
JJJApplication.prototype.hideHelp = function()
{
	this.hidePopup();
	/*if(this.helpVisible){
		var helpDiv = $('help');
		helpDiv.parentNode.removeChild(helpDiv);
		this.helpVisible = false;
	}*/
}

/********************************
* enlarges page text
* pass true if you don't want to change
* current value. ie turning it after loading cookie
*********************************/
JJJApplication.prototype.setFontSize = function(noChange)
{
	var main = document.getElementsByTagName('body').item(0);// get body tag
	
	if (!noChange) {
		//only change setting if we want to
		this.savedSettings.largeFont = !this.savedSettings.largeFont;
	}
	
	if (this.savedSettings.largeFont) {
		//apply largetext class to body
		$('texttool').setAttribute('help','Make Text Smaller');
		main.className = 'largeText';
		MM_swapImage('textimg','','/images/tools/textSize_on.gif',1);

	} else {
		//remove the class
		$('texttool').setAttribute('help','Make Text Bigger');
		main.className = '';
		MM_swapImgRestore();
	}	
		
	this.savedSettings.saveSettings();
}

/********************************
* returns array of forms input values
* if they are checked.
*
* fromName: Name of the form to look for
* formInputName: name of the checkboxes to get values from
*********************************/
JJJApplication.prototype.getInputArray = function(formName, formInputName) {
	var inputs = document.forms[formName][formInputName];
	var values =  new Array();
	for(var i = 0;i < inputs.length;i++) {
		if(inputs[i].checked)
			values.push(inputs[i].value);
	}

	return values;
}

/********************************
* saves the worktype by getting the
* values of the checkboxs in the form
*
* fromName: Name of the form to look for
* name of the checkboxes to get values from
***************************************/
/*JJJApplication.prototype.saveWTSearch = function(formName, formInputName) {
	this.savedSettings.wt = this.getInputArray(formName, formInputName);
	this.savedSettings.saveSettings();
}*/

/*************************************
* saves the Category by getting the
* values of the checkboxs in the form
*
* formName: Name of the form to look for
* name of the checkboxes to get values from
***************************************/
/*JJJApplication.prototype.saveCategorySearch = function(formName, formInputName) {
	this.savedSettings.occ = this.getInputArray(formName, formInputName);
	this.savedSettings.saveSettings();
}*/

/*****************************************
* saves the form search settings to the 
* savedSettings object, uses the forms input
* names as class member accessors
*
* formname: the form to save 
******************************************/
JJJApplication.prototype.saveSearch = function(formName) {
	var el = document.forms[formName].elements;//get all form elements
	for(var i = 0;i < el.length;i++) { 	//for each form element
		var value = null;
		var name = el[i].name;
		
		switch (el[i].type) {	//input type
		
			case 'checkbox': //currently all check boxes are array of sames names
				//if(el[i].checked)
					value = this.getInputArray(formName,name);//gets all the values of same named checkboxes in an array
				break;
				
			case 'text':
				//if(el[i].value != "")
					value = el[i].value;
				break;
				
			case 'search':
				//if(el[i].value != "")
					value = el[i].value;
				break;
				
			case 'select-one':
				
				if (el[i].selectedIndex!=-1) {
					if (el[i].options[el[i].selectedIndex].value != "") {
						value = new Array(el[i].options[el[i].selectedIndex].value);
					}
				}
				
			case 'select-multiple':
				value = new Array();
				for(var j = 0;j < el[i].length;j++) {
					if (el[i].options[j].selected) {
						value.push(el[i].options[j].value);
					}
				}
				break;
					
			default:
				break;
		}
			
		if (value != null) {
			this.savedSettings[name] = value;//save the value in the object, use it's name to reference it
		}
	}
	
	this.savedSettings.saveSettings();//tell object to write cookies
}


/**************************************
* selects passed forms inputs with
* saved settings in savedSettings Object
*
* formName: the form to update
* elementName: the element to update
* if elementName is blank, all elements are update
* else only elements matching that name are updated
****************************************/
JJJApplication.prototype.updateForm = function(formName, elementName) {
	var el = document.forms[formName].elements;//get all form elements
	for(var i = 0;i < el.length;i++) { //for each form element
		
		var name = el[i].name;
		
		if ((elementName == '') || (name == elementName)) {
		
		switch (el[i].type) {	//input type
			case 'checkbox':
				var selected = false;
				var arr = this.savedSettings[name];
				for(var j = 0;j < arr.length;j++) { 	// loop through stored values to find ones we need to select
					if (arr[j] == el[i].value) { 			//selected value found so select it
						selected = true;
					}
				}
				
				//if (arr.length == 0||arr[0]==0) {		//if array is empty or value is 0 then we should select all in the group for business rules
				if (arr.length == 0) {						//if array is empty then we should select all in the group for business rules
					selected = true;
				}
					
				el[i].checked = selected;
				break;
				
			case 'text':
				el[i].value = this.savedSettings[name];
				break;
				
			case 'search':
				el[i].value = this.savedSettings[name];
				break;
				
			case 'select-one':
			  	var value = this.savedSettings[name];
				
				if (typeof(value)=='object') {
					value = value[0];
				}
					
				for(var j = 0;j < el[i].length;j++) {
					if (el[i].options[j].value ==  value) {
						el[i].options[j].selected = true;				//found match so select it
					}
				}
				break;
			
			case 'select-multiple':
			  	var value = this.savedSettings[name];
				for(var j = 0;j < el[i].length;j++) {
					for(var l = 0;l<value.length;l++) {
						if (el[i].options[j].value ==  value[l]) {
							el[i].options[j].selected = true;			//found match so select it
						}
					}
				}
				break;
					
			default:
				break;
		}
		}
	}
}

JJJApplication.prototype.displayAdInfo = function(event, sid) {

	var html = '<img src="/images/spinnersmall.gif" />';
	this.createPopup(event, html, sid, false);

	var d = new Date();
	var time = d.getTime();

	var url = adInfoPath;

	// var pars = 'oid=' + encodeURIComponent(oid);					//+ind
	var pars = 'SID=' + sid + '&time=' + time;

 	if(this.adRequest){
 		if (callInProgress(this.adRequest.transport)) {
 			this.adRequest.transport.abort();
 			clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
 		}
 	}
	this.adRequest = null;
	var app = this;//save this for callback

// 	this.ajaxWait = window.setTimeout(function(){
// 	app.adRequest = new Ajax.Request( 
// 		url, 
// 		{
// 			method: 'get', 
// 			parameters: pars,
// 			onComplete: function(obj){app.updateAdInfo(obj);}
// 		});
// 	},600);

	app.adRequest = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onComplete: function(obj){app.updateAdInfo(obj);}
		});
}

JJJApplication.prototype.displayAdInfoPreview = function(event, sid) {

	var html = '<img src="/images/spinnersmall.gif" />';
	this.createPopup(event, html, sid, false);

	var d = new Date();
	var time = d.getTime();

	var url = adInfoPreviewPath;

	// var pars = 'oid=' + encodeURIComponent(oid);						//+ind
	var pars = 'SID=' + sid + '&Preview=1' + '&time=' + time;		// This is a test preview only

 	if(this.adRequest){
 		if (callInProgress(this.adRequest.transport)) {
 			this.adRequest.transport.abort();
 			clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
 		}
 	}
	this.adRequest = null;
	var app = this;//save this for callback

// 	this.ajaxWait = window.setTimeout(function(){
// 	app.adRequest = new Ajax.Request( 
// 		url, 
// 		{
// 			method: 'get', 
// 			parameters: pars,
// 			onComplete: function(obj){app.updateAdInfo(obj);}
// 		});
// 	},600);

	app.adRequest = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onComplete: function(obj){app.updateAdInfo(obj);}
		});
}

JJJApplication.prototype.displayRdInfo = function(event, rid, ind) {

	var html = '<img src="/images/spinnersmall.gif" />';
	this.createPopup(event,html,rid,false);

	var d = new Date();
	var time = d.getTime();

	var LocationArray = new Array();
	LocationArray = this.getInputArray('sideForm', 'cs')

	var LocationString = "";
	for (i = 0; i < LocationArray.length; i++) {
		LocationString += "&cs=" + encodeURIComponent(LocationArray[i]);
	}
	var url = rdInfoPath;

	//var pars = 'rid='+encodeURIComponent(rid);//+ind
	var pars = 'RID=' + encodeURIComponent(rid) + 
					'&ind=' + encodeURIComponent(ind) +
					LocationString +
					 '&time=' + time;

	if (this.adRequest) {
		if (callInProgress(this.adRequest.transport)) {
			this.adRequest.transport.abort();
			clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
		}
	}
	this.adRequest = null;
	var app = this;//save this for callback

	app.adRequest = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onComplete: function(obj){app.updateAdInfo(obj);}
		});

}

JJJApplication.prototype.updateAdInfo = function(request) {
	$('popup_content').innerHTML = request.responseText;
}

/**************************************
* Displays a popup at the mouse position
*
* innerHTML: the html to put in the popup
* scope: pass a string, if the scope is different
* than the last one, a new popup is displayed.
* large: use larger style, bool
* x_offset,y_offset - if defined and non-zero
*   sets relative popup position
***************************************/
JJJApplication.prototype.createPopup = function(event,innerHTML,scope,large,x_offset,y_offset) {
		if (!x_offset) {x_offset = -40;}
		if (!y_offset) {y_offset = 1;}

		if(this.popUpscope == scope||scope==null) {
			clearTimeout(this.timeout);
		} else {
			//new scope
			this.popUpscope=scope;	
			$('popup').style.display = 'none';
			clearTimeout(this.timeout);
			if(this.adRequest){
				if (callInProgress(this.adRequest.transport)) {
					this.adRequest.transport.abort();
					clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
				}
			}
		}

		if($('popup').style.display == 'none') {
			if(large)
				$('popup').className = 'popupLarge';
			else
				$('popup').className = 'popup';
			$('popup_content').innerHTML = innerHTML;
			
			var screenwidth;

			if (navigator.appName.indexOf("Microsoft") != -1) {
				screenwidth = document.body.offsetWidth;
			} else {
				screenwidth = window.innerWidth;
			}

			var posx;

			if (!event) var event = window.event;
			if (event.pageX || event.pageY) {
				posx = event.pageX;
			} else if (event.clientX || event.clientY) {
				if (document.documentElement) {
					posx = event.clientX + document.documentElement.scrollLeft;
				} else {
					posx = event.clientX + document.body.scrollLeft;
				}
			}

			var popup_width = Element.getDimensions($('popup')).width;
			if (popup_width + posx + x_offset >= screenwidth) {
				// pop is at edge of screen, flip it so it offsets to the left instead of the right
				$('popup').className += " popupFlip"; //add the flip css
				x_offset = -(x_offset + popup_width); //include popup width in offset
			}
			setPos(event, $('popup'),{x:x_offset, y:y_offset});
			
			this.timeout = setTimeout(function(){new Effect.Appear('popup', {duration:.3, fps:40})},400);
		}
}

/************************
* hides popup
*************************/
JJJApplication.prototype.hidePopup = function() {
	
	//var popup = $('popup');
	
	//if(popup == undefined)
	clearTimeout(this.ajaxWait);
	if ($('popup').style.display == 'none') {
		clearTimeout(this.timeout);
	} else {
		var obj = this;
		this.timeout = setTimeout(function() {
						if(obj.adRequest != null) {
							if (callInProgress(obj.adRequest.transport)) {
								obj.adRequest.transport.abort();
								clearTimeout(obj.adRequest['timeoutId']);//need to clear global timeout if we abort
							}
						}
		   
						new Effect.Fade('popup', {duration:.3, fps:40})
					},300);
	}

}

JJJApplication.prototype.displayLogin = function(event) {

	// this.loginPopuptimeout                 - animate the login popup
	// this.fieldsUnderneathLoginPopuptimeout - animate changes in firsttime/startform cs/Location field
		
	clearTimeout(this.loginPopuptimeout);
	clearTimeout(this.fieldsUnderneathLoginPopuptimeout);

	if($('popupLogin').style.display == 'none'){
		setPos(event, $('popupLogin'),{x:-40,y:0});
		this.loginPopuptimeout = setTimeout(function() {
					new Effect.Appear('popupLogin', {duration:.3, fps:40})
				},400);
	}

}

JJJApplication.prototype.hideLoginPopup = function(event, content) {

	// this.loginPopuptimeout - animate the login popup
	// this.loginstartformtimeout - animate changes in firsttime/startform cs/Location field

	if (!content) {
		if ($('popupLogin').style.display == 'none') {
			clearTimeout(this.loginPopuptimeout);
			clearTimeout(this.fieldsUnderneathLoginPopuptimeout);
		} else {
			this.loginPopuptimeout = setTimeout(function() {
						new Effect.Fade('popupLogin', {duration:.3, fps:40})
					},100);
		}
	} else {
		//alert(event);
		event.stopPropagation();
	}
}

JJJApplication.prototype.highlightTagCloud = function(arrayOfIds,tagCloudID) {
	var cloud = $(tagCloudID).getElementsByTagName('a');
	for(var j = 0;j<cloud.length;j++) {
		cloud[j].className = '';//clear all the tags
	}
	
	for(var i = 0;i<arrayOfIds.length;i++) {
		$(arrayOfIds[i]).className = 'current';
	}

}

JJJApplication.prototype.unHighlightTagCloud = function(arrayOfIds) {
	for(var i = 0;i<arrayOfIds.length;i++) {
		$(arrayOfIds[i]).className = '';
	}

}


/*
* Toggle Ipod terms and conditions
*/
JJJApplication.prototype.toggleIpodTerms = function() {
	new Effect.toggle($('ipodTerms'), 'blind');
		if (this.IpodTermsClosed == 1) {
			this.IpodTermsClosed = 0;
			$('IpodHref').innerHTML = '* Show iPod Shuffle terms and conditions';
		} else {
			this.IpodTermsClosed = 1;
			$('IpodHref').innerHTML = '* Hide iPod Shuffle terms and conditions';
		}
}

/************************
* close popup
*************************/
JJJApplication.prototype.closePopup = function(popupid) {
	if (external_popup && timer) {
		clearInterval(timer);
	}
	externalCounted = 0;

	$(popupid).style.display = "none";
	
	// For IE6 need to show the select controls
	showHideSelectControls(false);
}

/************************
* open / close search locations side bar tool.
*************************/
JJJApplication.prototype.openCloseLocation = function(locationid, locationimgid) {

	if (this.locationSearchPage == 1) {
		// Toggle the Locations open. Set the Img Tag to minus.jpg
		this.locationSearchPage = 0;
		$(locationimgid).src = "/images/icons/minus.gif";
		$(locationimgid).alt = "[Location close image]";
	} else {
		// Toggle the Locations closed. Set the Img Tag to plus.jpg
		this.locationSearchPage = 1;
		$(locationimgid).src = "/images/icons/plus.gif";
		$(locationimgid).alt = "[Location open image]";
	}

	new Effect.toggle(locationid,'slide',{duration:0.2,queue:'end'});
}

/************************
* open / close search locations View all side bar tool.
* Make the appropriate Div show / hide.
*************************/
JJJApplication.prototype.LoceyeViewAllopenClose = function(locationid, ahrefid) {

	if (this.locationViewAll == 1) {
		// Change Text 'View all'
		//$(ahrefid).innerHTML = "View all";
		this.locationViewAll = 0;
		new Effect.toggle('locationEyeTop','slide',{duration:0.2,queue:'end'});
		// close the Bottom "View less" div.
		new Effect.toggle('locationEyeBottom','slide',{duration:0.2,queue:'end'});

	} else {
		// Change Text to 'View less'
		//$(ahrefid).innerHTML = "View less";
		this.locationViewAll = 1;
		new Effect.toggle('locationEyeBottom','slide',{duration:0.2,queue:'end'});
		// close the Top "View all" div.
		new Effect.toggle('locationEyeTop','slide',{duration:0.2,queue:'end'});

	}

	new Effect.toggle(locationid,'slide',{duration:0.2,queue:'end'});
}

/************************
* Save CityState when search location side bar selected.
* We also have to clear any regions that are selected.
*************************/
JJJApplication.prototype.saveCityState = function(citystate) {

	if (citystate) {
		// Save the CityState passed into the select control.
		document.forms['sideForm'].cs.length = 0;
		document.forms['sideForm'].cs.options[0] = new Option("", citystate, false, true);
		// Untick any of the region hidden checkboxes.
		
		var RGcheckboxen = document.forms['sideForm'].rg;

		// Check that the check box group has more than one element
		if(RGcheckboxen.length > 0) {
			// Loop through the array
			for (i = 0; i < RGcheckboxen.length; i++) {
				RGcheckboxen[i].checked = false;
			}
		} else {
			// One check boxen to clear.
 			RGcheckboxen.checked = false;
		}
	}
}

/*******************************
*	Pretty the URL's for printing
*	Will allow all urls without http://
* 	part to have a http:// part.
*  
********************************/
JJJApplication.prototype.prettyURL = function() {

	var xurl = document.getElementsByTagName("a");

	for (i = 0; i < xurl.length; i++) {
		xurl[i].href = xurl[i].href;
	}

}

/*******************************
*	Save the Tag cloud Industry (Job Category) and/or Occupation (sub Category)
*  into the lastSearch Cookie
********************************/
JJJApplication.prototype.saveTagCloud = function(industry, occupation) {

	// this references the SaveSettings Object to do the saving.	
	this.savedSettings.saveTagCloudToCookie(industry, occupation);
}

/*******************************
*	Clear the Job Sub-category Checkboxes when the All Job Sub-categories
*  Checkbox is ticked.
********************************/
JJJApplication.prototype.ClearJobSubCategoryTicks = function(formName) {

	var OCCcheckboxen = document.forms[formName].occ;

	// Check that the check box group has more than one element
	if(OCCcheckboxen.length > 0) {
		// Loop through the array
		for (i = 0; i < OCCcheckboxen.length; i++) {
			if (OCCcheckboxen[i].value == 0) {
				OCCcheckboxen[i].checked = true;
			// Do not clear special null sub-category (8888)
			} else if (OCCcheckboxen[i].value != 8888) {
				OCCcheckboxen[i].checked = false;
			}
		}
	} else {
		// One check boxen to clear.
		if (OCCcheckboxen.value == 0) {
			OCCcheckboxen.checked = true;
		// Do not clear special null sub-category (8888)
		} else if (OCCcheckboxen[i].value != 8888) {
			OCCcheckboxen.checked = false;
		}
	}
}

/*******************************
*	Clear the All Job Sub-categies Checkboxes when any of the individual
*	Job Sub-category Checkboxes is ticked.
*	Exception is if this was the last individual checkbox being unticked,
*	then we select the All Job Sub-categies checkbox.
********************************/
JJJApplication.prototype.ClearAllJobSubCategoryTick = function(formName) {

	var OCCcheckboxen = document.forms[formName].occ;
	var checkedval = true;	// Set all sub categories (unless something else selected)

	// Check that the check box group has more than one element
	if(OCCcheckboxen.length > 0) {
		// If there are no sub-categories left selected, we need to select
		// the all sub-categories check box, else we clear it.
		// Loop through the array, and check if any check boxes still selected
		for (i = 0; i < OCCcheckboxen.length; i++) {
			if ((OCCcheckboxen[i].value != 0) &&
				 (OCCcheckboxen[i].value != 8888) &&
				 (OCCcheckboxen[i].checked == true)) {
				checkedval = false;	// We need to clear the all sub-categories check box
			}
		}
			
		// Loop through the array and set the all sub-categories check box
		for (i = 0; i < OCCcheckboxen.length; i++) {
			if (OCCcheckboxen[i].value == 0) {
				OCCcheckboxen[i].checked = checkedval;
			}
		}
	} else {
		// One check boxen to clear.
		// If only have 1 check box, allow it to clear (all sub-categories
		// doesn't make much sense in this context).
		if (OCCcheckboxen.value == 0) {
			OCCcheckboxen.checked = false;
		}
	}
}


/******** end main jjjApplication controller ********/

Effect.Center = function(element) {
	try {
		element = $(element);
	} catch(e) {
		return;
	}

	var my_width  = 0;
	var my_height = 0;

	if (typeof( window.innerWidth ) == 'number') {
		my_width  = window.innerWidth;
		my_height = window.innerHeight;
	} else if (document.documentElement && 
			(document.documentElement.clientWidth || document.documentElement.clientHeight)) {

		my_width  = document.documentElement.clientWidth;
		my_height = document.documentElement.clientHeight;
	} else if (document.body && 
			(document.body.clientWidth || document.body.clientHeight)) {

		my_width  = document.body.clientWidth;
		my_height = document.body.clientHeight;
	}

	element.style.position = 'absolute';
	// element.style.display  = 'block';
	if( !(element.style.zIndex) ) {
		element.style.zIndex   = 99;
	}

	var scrollY = 0;

	if (document.documentElement && document.documentElement.scrollTop) {
		scrollY = document.documentElement.scrollTop;
	} else if (document.body && document.body.scrollTop) {
		scrollY = document.body.scrollTop;
	} else if (window.pageYOffset) {
		scrollY = window.pageYOffset;
	} else if (window.scrollY) {
		scrollY = window.scrollY;
	}

	var elementDimensions = Element.getDimensions(element);
	var setX = ( my_width  - elementDimensions.width  ) / 2;
	var setY = ( my_height - elementDimensions.height ) / 2 + scrollY;

	setX = ( setX < 0 ) ? 0 : setX;
	setY = ( setY < 0 ) ? 0 : setY;

	element.style.left = setX + "px";
	element.style.top  = setY + "px";

};

function alertBox(errorString) {	

	var buttonHtml = '<button class="buttonSmall" style="float:none;margin-top:10px;" onclick="ToggleAlertBox();return false;"><span class="buttonText">Close</span></button>';

	if (errorString == "") {
		errorString = "An error has occurred. Please try again.<br><br>" +
						"If this error keeps appearing, " +
						"please report it along with what you were doing to support@jobsjobsjobs.com.au.";
	}
	$('alertBoxDialog').innerHTML = errorString + "<br>" + buttonHtml;
	
	ToggleAlertBox();

	return false;
}

function ToggleAlertBox() {
	var AlertBoxen = document.getElementById("alertBox");
	AlertBoxen.style.display = (AlertBoxen.style.display == "block") ? "none" : "block";
}

function showHideSelectControls(hide) {

	/* 	# %PUBLIC%
		# NAME:*		showHideSelectControls()
		# DESCR:*		Make the select controls on the Page visible / invisible.
		# :*			IE 6 select controls sit above every other z-index.
		# :*			sometimes we need to hide them so other things show on top.
		# :*			This function will show by default. If hide is true, then
		# :*			make the selects invisible.
		# USAGE:*		showHideSelectControls(hide);
		# RETURNS:*		Nothing. 
		# %ENDPUBLIC% */

	var selectControls = document.getElementsByTagName("select");

	if (hide == true) {
		// Hide the select controls.
		for (i = 0; i != selectControls.length; i++) {
			selectControls[i].style.visibility = "hidden";
		}

	} else {
		// Show the select controls.
		for (i = 0; i != selectControls.length; i++) {
			selectControls[i].style.visibility = "visible";
		}
	}
}

function findXY(elem) {
	// Give a document element, find it's window position (the X and Y offsets)
	// Return array of values [x position, y position] 
	var XY = [0,0];
	if (elem.offsetParent) {
		do {
			XY[0] += elem.offsetLeft;
			XY[1] += elem.offsetTop;
		} while (elem = elem.offsetParent);
	}
	return XY;
}

addAtrributeToLinks = function() {
	// if the site is called from the outer world we need to set few attributes
	var anc = document.links;
	var checkHome = /^(()|(\s+))Home((\s+)|())$/;
	for (var i=0; i<anc.length; i++) {
		if (checkHome.test(anc[i].innerHTML)) {
			anc[i].setAttribute('onclick',"navigateTop('" +anc[i].href +"')");
		}
	}
} 

function navigateTop(site) {
	parent.location.href= site;
}

/*************************************************************************
* New functions for popup login box
*************************************************************************/
function loginBox(errorString) {	

	if (errorString == "") {
		errorString = "A login error has occurred. Please try again.<br><br>" +
						"If this error keeps appearing, " +
						"please report it along with what you were doing to support@jobsjobsjobs.com.au.";
		alertBox(errorString);
	} else {
		$('loginBoxDialog').innerHTML = errorString;
		ShowLoginBox();
	}

	return false;
}

function ShowLoginBox() {

	// Show the login box div
	showBoxDiv($('loginBox'));
}

function HideLoginBox( oid ) {

	// Hide the login box div
	hideBoxDiv($('loginBox'));

	// Clear the contents
	$('loginBoxDialog').innerHTML = '';

	// Remove the spinner
	if( oid && $('spinner_'+oid) ) {
		new Effect.Fade('spinner_'+oid);
	}
}

JJJApplication.prototype.attemptLogin = function() {

        // -----------------------------------------
        // Create an ajax call to call the ajax 
        var app = this;//save this for callback
        var d = new Date();
        var time = d.getTime();

	// Some cosmetic stuff - if we have a connecting block show it
	if( $('connectingBtn') ) {

		if( $('loginBtn') ) {
			$('loginBtn').style.display = 'none';
		}
		$('connectingBtn').style.display = 'block';
	}

	var url = '/login?';
        var pars = 'time='+time;
        // Add bookmark flag to not display bookmark this job on barkmark list

        // Have they supplied login params if so lets pass them in as well
        if( $('authen_username') ) {
                pars += '&authen_username='+encodeURIComponent($('authen_username').value);
        }
        if( $('authen_password') ) {
                pars += '&authen_password='+encodeURIComponent($('authen_password').value);
        }
        if( $('loginfailed') ) {
                pars += '&loginfailed='+$('loginfailed').value;
        }

	if( $('rememberme') ) {
		pars += '&rememberme='+$('rememberme').value;
	}

        // With this call we don't care about other calls in progress
        // so we don't check for them.  We do show a response
        var theCall = new Ajax.Request(
                url,
                {
                        method: 'post',
                        parameters: pars,
                        onComplete: function(obj){app.ajaxResponse(obj);}
                });
}

JJJApplication.prototype.ajaxResponse = function(request) {

	HideLoginBox();  // Put it away we will pull it out again if needed

	// The request object will be treated as follows
	// Multiple returns ( split on __pjx__ )
	// text/html - Display in a loginBox ( content or error )
	// text/javascript - eg reload page
	var response = request.responseText.split('__pjx__');
	if( response.length == 2 ) {

		// We have 2 return items
		// 1 HTML - output via loginBox
		// 2 Javascript - evaluate
		loginBox(response[0]);
		eval(response[1]);

	} else {

		// Only 1 return item
		// Check content type for output
		var ct = request.getResponseHeader('Content-Type').split(';');

		if( ct[0] == 'text/javascript' ) {

			// Just use it, don't eval as will run twice
			request.responseText;

		} else {

			var response = request.responseText;
			var line = request.responseText.substring(0, 24);
			if( line == '<h1>Software error:</h1>' ) {
				//response = '<h1>Software error</h1><p>An error has occurred</p>';
				alertBox( response );
			} else {
				loginBox( response );
			}
		}
	}
}

/*************************************************************************
* New functions for dynamic ads - Bookmark/Save Job
*************************************************************************/
JJJApplication.prototype.bookmarkInstead = function( event, oid, isJOTD ) {

	// Remove the spinner
	if( $('spinner_'+oid) ) {
        	new Effect.Fade('spinner_'+oid);
	}

	var jotdVersion = 'JOTD_OID_'+oid;
	var stdVersion = 'OID_'+oid;
	var element = (isJOTD)?$(jotdVersion):$(stdVersion);
	var elementImg = $(((isJOTD)?jotdVersion:stdVersion)+'_save');

	// Close the login box is open
	HideLoginBox();

	if (document.createEventObject){

		// Toggle element state as IE fireEvent doesn't
		element.checked = (element.checked) ? false : true;

		// dispatch for IE
		// Set an expando property on the event object. 
		// This will be used by the event handler to 
		// determine what element was clicked on.

		var evt = document.createEventObject();
		evt.expando = element.id;
		element.fireEvent('onclick',evt);
		evt.cancelBubble = true;


	} else{

		var evt = document.createEvent("MouseEvents");
		// event type,bubbling,cancelable
		evt.initEvent('click', false, true ); 
		element.dispatchEvent(evt);
	}

	// Set our the checkbox status of standard job or JOTD is also present
	// Update all the images as well
        if ($(jotdVersion) && !(isJOTD)) {

		if( $(jotdVersion).checked ) {

			$(jotdVersion).checked = false;

		} else {

                	$(jotdVersion).checked = true;

		}
        }

	if($(stdVersion) && isJOTD) {

                if( $(stdVersion).checked ) {

			$(stdVersion).checked = false;

		} else {

			$(stdVersion).checked = true;

		}
	}
}

JJJApplication.prototype.saveJob = function(oid, isJOTD) {

	// -----------------------------------------
	// Create a spinner so we no it's in action
	var elName = 'spinner_'+oid;
        var el = $(elName);

        if(el != undefined) {
                el.parentNode.removeChild(el);
        }

        //create div and set attributes
        el = document.createElement('div');
        el.setAttribute('id',elName);
        el.innerHTML = '<img src="/images/spinner.gif" />';
	el.style.zIndex = 900;

        //insert the div before all else in the DOM's body
        var parent = document.getElementsByTagName('body').item(0);
        parent.insertBefore(el,parent.firstChild);
        new Effect.Center(elName);

        //work out position of job we are saving and locate the 'spinner' there 
	var order = document.getElementById((isJOTD)?'jotd_oid_'+oid+'_'+oid:'oid_'+oid+'_'+oid);
        if (order) {
                var pos = findXY(order); // array [xpos, ypos]
                if (pos[1]) {
                        el.style.top = pos[1] + 'px';
                }
        }

	// -----------------------------------------
	// Create an ajax call to call the ajax 
	var app = this;//save this for callback
	var d = new Date();
	var time = d.getTime();

	var url = '/savejob?';
	var pars = 'OID='+encodeURIComponent(oid)+'&JOTD='+((isJOTD)?1:0)+'&time='+time;
	// Add bookmark flag to not display bookmark this job on barkmark list

	// Have they supplied login params if so lets pass them in as well
	if( $('login_username') ) {
		pars += '&authen_username='+encodeURIComponent($('login_username').value);
	}
	if( $('login_password') ) {
		pars += '&authen_password='+encodeURIComponent($('login_password').value);
	}
	if( $('login_failed') ) {
		pars += '&loginfailed='+$('login_failed').value;
	}

	// Check if job is bookmarked.  If so don't show bookmark text
	pars += '&BMT='+((this.bookmarkedJobs[oid])?0:1);

	// With this call we don't care about other calls in progress
	// so we don't check for them.  We do show a response
	var theCall = new Ajax.Request( 
		url, 
		{
			method: 'post', 
			parameters: pars,
			onComplete: function(obj){app.ajaxResponse(obj);}
		});
}

JJJApplication.prototype.saveJobNotify = function(oid, message) {

	// Remove the spinner
	if( $('spinner_'+oid) ) {
        	new Effect.Fade('spinner_'+oid);
	}

	// Find any infobox instance and remove it
        var el = $('infoBox');
        if(el != undefined) {
                el.parentNode.removeChild(el);
        }

        //create div and set attributes
        el = document.createElement('div');
        el.setAttribute('id','infoBox');
        el.innerHTML = message;
	el.style.zIndex = 1000;

        //insert the div before all else in the DOM's body
        var parent = document.getElementsByTagName('body').item(0);
        parent.insertBefore(el,parent.firstChild);
        new Effect.Center('infoBox');

	var prefixes = ['OID_', 'JOTD_OID_', 'POPUP_OID_'];
	for (idx=0; idx<prefixes.length; idx++) {
		var jobimg = prefixes[idx]+oid+'_save';
		//if the jobs are listed update image
		if( $(jobimg) ) {
			$(jobimg).src = '/images/icons/save_grey.png';	
		}
	}

	if ($('ssjames') != undefined) {
                new Effect.Highlight('ssjames',{startcolor:'#333333',queue: {scope: 'highlight',position: 'end'}});
        }

        new Effect.Fade('infoBox',{queue: 'end'});
}

/*************************************************************************
* New functions for dynamic ads - Popup Job
*************************************************************************/
JJJApplication.prototype.popupJob = function(event, oid) {

	var html = '<img src="/images/spinnersmall.gif" />';
	this.createJobPopup(event, html, oid);

	var d = new Date();
	var time = d.getTime();

	var url = '/viewjob?rm=viewjob_popup';

	var pars = 'OID='+encodeURIComponent(oid)+'&time='+time;

 	if(this.adRequest){
 		if (callInProgress(this.adRequest.transport)) {
 			this.adRequest.transport.abort();
 			clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
 		}
 	}
	this.adRequest = null;
	var app = this;//save this for callback

	app.adRequest = new Ajax.Request( 
		url, 
		{
			method: 'get', 
			parameters: pars,
			onComplete: function(obj){app.updateJobPopup(obj);}
		});
}

JJJApplication.prototype.updateJobPopup = function(request) {
	$('popup_job_content').innerHTML = request.responseText;
}

JJJApplication.prototype.createJobPopup = function(event,innerHTML,scope,newClass) {
	if (external_popup && timer) {
		clearInterval(timer);
	}
	externalCounted = 0;
		
		if(this.popUpscope == scope||scope==null) {
			clearTimeout(this.timeout);
		} else {
			//new scope
			this.popUpscope=scope;	
			$('popup_job').style.display = 'none';
			clearTimeout(this.timeout);
			if(this.adRequest){
				if (callInProgress(this.adRequest.transport)) {
					this.adRequest.transport.abort();
					clearTimeout(this.adRequest['timeoutId']);//need to clear global timeout if we abort
				}
			}
		}

		if($('popup_job').style.display == 'none') {
			if(newClass != null) {
				$('popup_job').className = newClass;
			} else {
				$('popup_job').className = 'popup_job';
			}
			$('popup_job_content').innerHTML = innerHTML;
			
			/********* 25/5/07 modified code to flip popups ***/
			var screenwidth;

			if (navigator.appName.indexOf("Microsoft") != -1) {
				screenwidth = document.body.offsetWidth;
			} else {
				screenwidth = window.innerWidth;
			}

			var offset = 100;
			var posx = 0;
			var tmp = 0;

			if (!event) var event = window.event;
			if (event.pageX || event.pageY) {
				posx = event.pageX;
			} else if (event.clientX || event.clientY) {
				if (document.documentElement) {
					posx = event.clientX + document.documentElement.scrollLeft;
				} else {
					posx = event.clientX + document.body.scrollLeft;
				}
			}

			if(Element.getDimensions($('popup_job')).width+posx >= screenwidth) {
				//if pop is at edge of screen
				$('popup_job').className += " popupFlip"; //add the flip css
				setPos(event, $('popup_job'),{x:10-Element.getDimensions($('popup_job')).width,y:10});//offset the popup by its width
			} else {
				setPos(event, $('popup_job'),{x:10,y:10});
			}
			
			/****** end modified ****/

			//this.timeout = setTimeout(function(){new Effect.Appear('popup', {duration:.3, fps:40})},400);
			new Effect.Appear('popup_job', {duration:.3, fps:40});
			
			// For IE6 need to hide the select controls
			showHideSelectControls(true);
			
		}
}

JJJApplication.prototype.redirectExternalApplication = function(event, oid, portal, popupMessage, new_location) {

	if(external_popup) {
		if (timer) { 
			clearInterval(timer); 
		}
		if ($('connectingBtn')) {
			$('connectingBtn').style.display = 'none';
		}		
	}
	
	var popup_link_location =  new_location;
	if ( popupMessage && (/^\/apply/.test(new_location))) {
		var OID = new_location.replace(/\/apply\?OID\=/gi, ""); 
		if (this.selectedExternalApplicationOID.indexOf(OID) < 0) {
			new_location = new_location.concat('&ext_count=1');
			this.selectedExternalApplicationOID.push(OID);
		}
	}

	var load_popup = true;
	if ($('POPUP_OID_'+oid+'_apply')) {
		if ($('POPUP_OID_'+oid+'_apply').className == 'POPUP_OID_'+oid+'_apply_class') {
			load_popup = false;
		}
	} 
	
	if ( load_popup ) {
		external_popup = window.open(new_location,"");	
	} else {	
		return false;
	}
	
	var blocked = ( !(external_popup && external_popup.top) ) ? 1 : 0;

	if( popupMessage ) {
		if ( blocked ) { 			
			popup_link_location = popup_link_location.concat('&ext_count=1');   //ensure count increment for link
		}
		var html = '<p>This advertiser requires applications to be submitted via a custom application form.<br><br>Pop-up blockers may prevent the apply page from displaying.<br><br><div class=\'exclamationWarning\' style=\'float:left;padding:2px 0px;\'></div><div style=\'float:left;padding:0px 5px;\'>Please <a href="'+popup_link_location+'">click here</a><br>to apply</div><div class=\'clear;\'></div></p>';
		this.createPopup( event, html, oid, false );
	} else {
		if ( blocked && (this.blockedExternalApplicationOID.indexOf(oid) < 0) ) {
			this.blockedExternalApplicationOID.push(oid);
		} 	
		timer = setInterval('polling()',1000);
	
		$('initExtText').style.display = 'none';
		$('applyButt').style.display = 'none';		
		$('extText').style.display = 'block';
		$('applyContainer').style.border = '1px dashed #000';
		$('applyContainer').style.background = '#FFFFCC';
		
		$('POPUP_OID_'+oid+'_apply').src = '/images/icons/apply_grey.png';
		$('POPUP_OID_'+oid+'_apply').onclick = 'return false;';  // doesn't work in firefox so validate against new  
																 // classname to prevent new window from loading
		$('POPUP_OID_'+oid+'_apply').className = 'POPUP_OID_'+oid+'_apply_class';
		
		Effect.Appear('connectingBtn',{ duration:.3, fps:40 });	
	}

	// Unless we are redirecting to /apply, we need to count the external application
	// if it hasn't been blocked
	if (!(/^\/apply/.test(new_location)) && (externalCounted == 0) && !blocked) {
		// Create an ajax call to update the external application counter
		var d = new Date();
		var time = d.getTime();

		var url = '/viewjob?rm=countexternal';

		var pars = 'OID='+encodeURIComponent(oid)+'&P='+encodeURIComponent(portal)+'&time='+time;

		// With this call we don't care about other calls in progress
		// so we don't check and don't store
		var theCall = new Ajax.Request( 
			url, 
			{
				method: 'get', 
				parameters: pars
			}
		);
		externalCounted = 1;
	}

	return false;
}


JJJApplication.prototype.updateExtAppCount = function(oid, portal, new_location) {
	var increment_counter = (this.blockedExternalApplicationOID.indexOf(oid) > -1) ? true : false;

	if ( increment_counter ) {
		// Create an ajax call to update the external application counter
		var d = new Date();
		var time = d.getTime();

		var url = '/viewjob?rm=countexternal';

		var pars = 'OID='+encodeURIComponent(oid)+'&P='+encodeURIComponent(portal)+'&time='+time;

		// With this call we don't care about other calls in progress
		// so we don't check and don't store
		var theCall = new Ajax.Request( 
			url, 
			{
				method: 'get', 
				parameters: pars,
				onComplete: function(transport) {
					document.location = new_location;
 				}
			}
		);
	} else {
		document.location = new_location;	
	}
		
	return false;	
}


function isIE6() {
	// Only interested in detecting IE6. Return '1' if it is, else '0'.
	return (/MSIE 6/.test(navigator.userAgent)) ? 1 : 0;
}

function polling(){
	if (external_popup && external_popup.closed) {
		clearInterval(timer);
		if ($('connectingBtn')) {
			new Effect.Fade('connectingBtn', { duration:.3, fps:40 });
		}
	} else if (external_popup) {
		if ($('connectingBtn')) {
			$('connectingBtn').style.display = 'block';
		}
	}
}

/*************************************************************************
* Common functions for login and jobspotter popup boxes
*************************************************************************/

function showBoxDiv(boxDiv) {

	// For IE6 need to hide the select controls
	showHideSelectControls(true);
	
	// Show the box
	boxDiv.style.display = "block";

	// For IE6 need to define an element height
	if (isIE6()) {
		var height = document.body.clientHeight;
		if (height) {
			boxDiv.style.height = height;
		}
	}
}

function hideBoxDiv(boxDiv) {

	// For IE6 need to show the select controls previously hidden
	showHideSelectControls(false);

	// Hide the box
	boxDiv.style.display = "none";
}

// Handle our onLoad functions here. The following allows us to keep any onLoad event from the
// base classes and run our functions on page load as well.

function addPageLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
