/*
Holds a number of functions that will be included on all jobboard pages as they are used throughout the site.
*/
function GetBody(){
	return document.getElementsByTagName("body")[0] || document.body;
}
function addClass(e,c)
{	
	if (e.className==undefined)
		e.className = c;
	else
		if (!hasClass(e,c))
			e.className += ' ' + c;
}

function delClass(e,c)
{
	if (e.className!=undefined)
		if (e.className.split(' ').length > 1)
			e.className = e.className.replace(new RegExp(' ' + c + '\\b'), '');
		else
			e.className = e.className.replace(new RegExp(c + '\\b'),'');
}

function hasClass(e,c)
{
	if (e.className!='')
	{
		cs = e.className.split(' ');
		for(i=0; i<cs.length; i++)
			if (cs[i]==c) return true;
	}
	return false;
}
//swap classA on element with classB. The two will never exist as same time.
function swapClass(e,cA,cB)
{
	if(hasClass(e,cA)){
		delClass(e,cA);
	}
	if(!hasClass(e,cB)){
		addClass(e,cB);
	}
}

function toggleClass(e,c)
{
	if (hasClass(e,c))
		delClass(e,c);
	else
		addClass(e,c);
}

function fncGetEmailAddr(strMailbox, strFQDN) {
	return strMailbox +'@'+ strFQDN;
}

function WinParam(p){if(p=="off" || p=="no" || p=="0" || p==0){return false;}else if(p=="on" || p=="yes" || p=="1" || p==1){return true;}else if(p){return true;}else{return false;}}

// Bookmark site
function bookmarksite(title, url){
	if (document.all)
		window.external.AddFavorite(url, title);
	else if (window.sidebar)
		window.sidebar.addPanel(title, url, "")
}

function OpenWin(url)
{	
	//backward compatibility use this function to call the new function
	OpenNewWin('win',200,265,0,0,0,0,1,0,0,0,url,'win',"");
}

//full comprehensive win opener
function OpenNewWin(strName,Width,Height,TOP,LEFT,Resizable,Status,Scrollbars,Titlebar,ToolBar,MenuBar,URL,TYPE,dArg)
{
	//alert("in OpenNewWin")
	//showModalDialog is the inverse of window.open, if you don't pass any params in for attributes
	//it will take it that you want them on not off! So best to always set paramater values.
	
	if(TOP==0 && LEFT==0){
		LEFT=(screen.width)?(screen.width-Width)/2:100;
		TOP=(screen.height)?(screen.height-Height)/2:100;
	}
		
	if (TYPE=="modal" && document.all)
	{
		var sF=""
		var _rv;
		sF+='unadorned:'+(WinParam(Titlebar)?'1;':'0;');
		sF+='help:'+(WinParam(ToolBar)?'1;':'0;');
		sF+='status:'+ (WinParam(Status)?'1;':'0;');
		sF+='scroll:'+(WinParam(Scrollbars)?'1;':'0;');
		sF+='resizable:'+ (WinParam(Resizable)?'1;':'0;');
		sF+=Width?'dialogWidth:'+Width+'px;':'';
		sF+=Height?'dialogHeight:'+(parseInt(Height)+(WinParam(Status)?42:0))+'px;':'';
		sF+=TOP?'dialogTop:'+TOP+'px;':'';
		sF+=LEFT?'dialogLeft:'+LEFT+'px;':'';
		if (TYPE=="modal"){		
			//alert("modal = " + sF);
			_rv=window.showModalDialog(URL,dArg?dArg:"",sF);
			if ("undefined" != typeof(_rv) )
				return _rv;
		}
	}else{
		var sF="";
		sF+=Width?'width='+Width+',':'';
		sF+=Height?'height='+Height+',':'';
		sF+=TOP?'top='+TOP+',':'';
		sF+=LEFT?'left='+LEFT+',':'';
		sF+='resizable='+ (WinParam(Resizable)?'1,':'0,');
		sF+='status='+ (WinParam(Status)?'1,':'0,');
		sF+='scrollbars='+(WinParam(Scrollbars)?'1,':'0,');
		sF+='titlebar='+(WinParam(Titlebar)?'1,':'0,');
		sF+='toolbar='+(WinParam(ToolBar)?'1,':'0,');
		sF+='menubar='+(WinParam(MenuBar)?'1,':'0,');		
		URL = URL?URL:'about:blank';
		strName = strName?strName.replace(/ /gi,""):'win';	//remove any gaps in the name for the window			
		//alert("window.open('" + URL + "','" + strName + "','" + sF + "')");
		_rv = window.open(URL,strName,sF);
		//alert(_rv + " - " + typeof(_rv));
		return _rv;
	}
}

function JobScroller(scrollerID, NoJobs, NoJobsVisible)
{
	//alert("create scroller for " + scrollerID + " noJobs = " + NoJobs + " NoVis = " + NoJobsVisible)
	var self = this;
	var isIE6 = false;
	//set flag if we are ie6
	/*@cc_on
	  @if (@_jscript_version == 5.6)
	    isIE6 = true;	  
	  @end
	@*/

	var StartDelay	= 2000; //Specify initial delay before marquee starts to scroll on page (2000=2 seconds)
	var ScrollSpeed	= 1;   //Specify scroll speed (larger is faster 1-10)
	var DoPause		= 1;  //1 = allow pausing when highlighted with mouse 0 = no pause
	
	
	this.CopySpeed = ScrollSpeed;
	this.PauseSpeed = (DoPause==0) ? this.CopySpeed:0;
	this.ActualHeight='';
	
	var ScrollerName = "ScrollJobs" + scrollerID;
	var ContainerName= "ScrollJobsContainer" + scrollerID;
	
	this.Scroller	= document.getElementById(ScrollerName);
	this.Container	= document.getElementById(ContainerName);
	
	this.Scroller.style.top = 0;	
	this.ScrollerHeight		= this.Container.offsetHeight;
	
	//if its not ie6 and we have more jobs than can be shown then tweak
	if(!isIE6 && NoJobs>NoJobsVisible){
		//work out the height per visible job
		var jobHeight = parseInt(this.ScrollerHeight / NoJobsVisible);
		//now calculate the extra height for all the jobs we can't see
		this.ActualHeight	= parseInt(jobHeight*NoJobs)+16;
		
	}else{ //should be ok in all browsers
		this.ActualHeight	= this.Scroller.offsetHeight;
	}
	//alert("ScrollerHeight = " + this.ScrollerHeight + " ActualHeight = " + this.ActualHeight)

	//if Opera or Netscape 7x, add scrollbars to scroll and exit
	if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ 
		this.Scoller.style.height=this.ScrollerHeight+"px";
		this.Sroller.style.overflow="scroll";
		return;
	}	
	
	addEvent( self.Container, 'mouseover', function(){self.CopySpeed=self.PauseSpeed;} );
	addEvent( self.Container, 'mouseout', function(){self.CopySpeed=ScrollSpeed;} );	
		
	setTimeout(function(){lefttime=setInterval(function(){self.ScrollJobs();},30);}, StartDelay);		
}

var flag = false;

//this should work in all browsers
JobScroller.prototype.ScrollJobs=function()
{
	
	var scroller = this.Scroller;
		
	// IE6 won't like *5.5!   Originally:  
	if (parseInt(scroller.style.top)>(this.ActualHeight*(-1)+8)){  // Original code (works fine in IE6, but disappears after about 8 jobs in IE7/FF.		
		scroller.style.top=parseInt(scroller.style.top)-this.CopySpeed+"px";
	}else{
		scroller.style.top=parseInt(this.ScrollerHeight)+8+"px";
	}
}

// My Cross browser functions for accessing form elements. Use the appropriate function for the HTML element you need
// Return a reference to an element by id
function getEl(id,doc)
{
	if(!doc) { doc = document; }
	if( doc.layers ) {
		if( doc.layers[id] ) { 
			return doc.layers[id]; 
		}else {
			for( var x = 0, y, l = doc.layers.length; !y && x < l; x++ ) {
				y = getEl(id,doc.layers[x].document); 
			}
			return y; 						
		}
	}else if(document.getElementById){
		return doc.getElementById(id);       
	}else if(document.all){
	   return doc.all[id];
	} 
	return document[id];
}
// Return a reference to a flash movie
function getFlashMovie(movie)
{
	var flash = (window[movie]) ? window[movie] : document[movie]; //this should cover most bases IE/Moz
	if(!flash){ //just in case it doesn't (who knows what the future may bring)
		if (document.embeds && document.embeds[movie]) //embeds should work in Moz
	      return document.embeds[movie]; 
		else{ return document.getElementById(movie);} //IE will hit this baby
	}
}
// Return a reference to an iframe element
function getIframe(id){
	var iframe;
	if(document.getElementById){
		return document.getElementById(id);	
	}else if(window.frames && window.frames.length){
		return window.frames[id];
	}	
}
// Return a reference to an iframe window element
function getIframeWin(iframe){
	if(iframe){
		if(iframe.contentWindow){
			return iframe.contentWindow;
		}else if(iframe.contentDocument && Browser && Browser.BrowserName=="Opera"){
			return iframe.contentDocument;		
		}else{
			return iframe;
		}		
	}
}//Return a reference to the document inside an iframe
function getIframeDoc(iframe){
	if(iframe){
		if(iframe.contentDocument){
			return iframe.contentDocument;
		}else if(iframe.contentWindow.document){
			return iframe.contentWindow.document;
		}else if(iframe.document){
			return iframe.document;
		}	
	}
}
//used in functions where either an object reference or an id to an element can be passed in
function getObj(el){
	return (!el)?document:(typeof(el)=="string")?getEl(el):el;
}


function setText(el,txt){
	el = getObj(el);
	if(el && txt){
		// I test in order of most common browser first for speed as 75% of users still use IE
		// try for w3c standard
		// IEs
		if(el.innerText){
			el.innerText = txt;
		// Moz
		}else if(el.textContent){
			el.textContent = txt;
		// w3c DOM implementation
		}else if(document.createElement){
			if(el.firstChild){
				el.firstChild.nodeValue=txt;
			}else{
				el.appendChild(document.createTextNode(txt));
			}
		}
	}
}

function getText(el){
	el = getObj(el);
	var txt="";
	if(el){
		// I test in order of most common browser first for speed as 75% of users still use IE
		if(el.innerText){
			txt = el.innerText;
		}else if(el.textContent){
			txt = el.textContent;			
		}else if(el.firstChild && el.firstChild.nodeType==3){
			txt = el.firstChild.nodeValue;
		}
	}
	return txt;
}
//lots of branches depend on whether the browser is IE or not
function IsIE(){
	var browserName = navigator.appName;	 	 
	if (browserName == "Microsoft Internet Explorer"){return true;}
	else{return false;};
}

// RJR func to return whether the browser is IE above or below a certain version. Call when certain code can only be run in IE6 or 7+
// If you just want to know whether its any version of IE call IsIE() (see above)
// vs=version to check browser, cm=1 is it above vs, cm=2 is it below vs, cm=0 is equal to vs
// return codes: -1 = not IE, 1 = matches check, 0 = doesn't match
function IsIEversion(vs,cm)
{	
	var r=-1; //default for non-IE
	var agt=navigator.userAgent.toLowerCase();
	var appVer=navigator.appVersion.toLowerCase();
	var is_mac=(agt.indexOf("mac")!=-1);	
	var iePos=appVer.indexOf('msie');
	if (iePos!=-1) {
	   if(is_mac) { var iePos = agt.indexOf('msie'); is_minor = parseFloat(agt.substring(iePos+5,agt.indexOf(';',iePos)));  }
	   else is_minor = parseFloat(appVer.substring(iePos+5,appVer.indexOf(';',iePos)));
	   is_major = parseInt(is_minor);	 
	}else{return r;}
	switch (cm)
	{
		case 0:
			if(is_minor==vs){r=1;}else{r=0;}
			break;
		case 1:
			if(is_minor>vs){r=1;}else{r=0;}
			break;
		case 2:
			if(is_minor<vs){r=1;}else{r=0;}
			break;
	}
	return r;
}
function IsFirefox(){
	if(Browser.BrowserName=="Firefox"){return true;}
	else{return false;}
}

function activateFlash()
{
	ShowDebug("IN activateFlash")
	var rc = Browser.opera;// IE has fixed their EOLAS issue but Opera needs it still
	ShowDebug("after rc = " + rc)
	ShowDebug("rc = " + rc + " isIEversion 6 or up = " + IsIEversion(5,1) + " is opera = " + Browser.opera);
	if(rc==1){				
		ShowDebug("Is IE need to activate flash with outerHTML object bodge");
		//make sure any flash objects are initialised and dont force user to click to activate
		objects = d.getElementsByTagName("object");for (var i = 0; i < objects.length; i++){objects[i].outerHTML = objects[i].outerHTML;}
		ShowDebug("Flash Activated");
	}else{
		ShowDebug("No need to activate flash not ie");
	}	
}

ScriptOnDemand = {}; //my script on demand object namespace
ScriptOnDemand.Loaded = Array(); //scripts already loaded through scripts on demand
ScriptOnDemand.Timers = {}; //for browsers using timers to handle callbacks contains timer references
ScriptOnDemand.LoadScript = function LoadScript(src,callbackFunc){
	//ShowDebug("IN ScriptOnDemand.LoadScript = " + callbackFunc);
	var b = Browser;		
	//can't do this on older browsers with no createElement support
    if(d.createElement){		
		var head= d.getElementsByTagName('head')[0];
		//check we haven't already loaded this script
		if(ScriptOnDemand.Loaded.indexOf(src)==-1){					
			//create a script element to add to the dom
			var script= d.createElement('script');
			script.setAttribute("type", "text/javascript");
			script.setAttribute("src", src);	
			//if we have a valid callback function
			if(typeof(callbackFunc)=="function"){
				//alert("do callback")
				//IE uses onreadystatechange and Firefox/Safari 3 support onload and Safari 2/Opera work with a timed interval
				script.onload = script.onreadystatechange = function(){
					if ( (!script.readyState || script.readyState == "loaded" || script.readyState == "complete") ) {						
						callbackFunc();
						head.removeChild(script); //remove script from head once loaded
						head=null;
						script=null;
					}
				}
				//handle older Safari and Opera use my basic browser object for sniffing
				if((b.name=="Safari"&&b.userAgent.match(/Version\/3/)) || b.opera){					
					ScriptOnDemand.Timers[src] = setInterval(function(){
							if(/loaded|complete/.test(d.readyState)){
								clearInterval(ScriptOnDemand.Timers[src]);
								callbackFunc();
								head.removeChild(script); //remove script from head once loaded
								head=null;
								script=null;
							}
						},25);
				}
			}
			script.onerror = function(){				
					throw("Error loading script: " + src + " " + e.toString());
					return true;
				}		
			head.appendChild(script);
		}else{ //if already loaded to dom then just call callback function
			if(typeof(callbackFunc)=="function"){
				callbackFunc();
			}
		}		
	}
}

function enumObj(obj){
	ShowDebug("IN enumObj");
	for(var x in obj){
		ShowDebug("obj["+x+"] = " + obj[x]);
	}
}

// RJR 01-Oct-08
// My helper object to parse current location querystring and return array of key/values, anchor tag.
// Also can pass in a querystring to parse/
function PageQuery(qry){
	ShowDebug("IN PageQuery = " + qry);
	
	this.ParamValues = {};
	this.ParamNo = 0;
	
	var CurrentQuery, AnchorValue = "";
	
	//if no querystring passed to constructor default to current location
	if(qry && qry.length>0){
		if(qry.substring(0,1)!="?") qry="?"+qry;
		CurrentQuery = qry;
	}else{
		if(location.search.length>0){
			CurrentQuery = location.href;
		}else{
			CurrentQuery = "";
		}
	}
		
	//may want to parse a query that is not the current window.location
	this.ParseQuery = function(qry){		
			ShowDebug("IN this.ParseQuery = " + qry);
			var rex = /[?&]([^=]+)(?:=([^&#]*))?/g;
			var rexa = /(\#.*$)/;
			var qmatch, key, amatch, cnt=0;
			ShowDebug("main regex = " + rex);
			//parse querystring storing key/values in the ParamValues associative array
			while(qmatch = rex.exec(qry)){
				key = denc(qmatch[1]);//get decoded key
				val = denc(qmatch[2]);//get decoded value
				ShowDebug("DO key " + key + " + val = " + val);
				if(this.ParamValues[key]){ //if we already have this key then update it if it has a value
					if(key&&key!="") this.ParamValues[key] = this.ParamValues[key] + ","+val;
				}else{
					this.ParamValues[key] = val;
					cnt++;
				}
			}
			//as no length property with associative arrays
			this.ParamNo = cnt; 
			//store anchor value if there is one
			ShowDebug("get anchor from " + qry + " reg = " + rexa);
			amatch = rexa.exec( qry );
			ShowDebug("match = " + amatch);
			if(amatch) AnchorValue = amatch[0].replace("#","");
			ShowDebug("Anchor = " + AnchorValue);
 
		}

	ShowDebug("CurrentQuery = " + CurrentQuery);
	//run function to parse querystring and store array of key/values and any anchor tag
	if(CurrentQuery.length){
		ShowDebug("Now Parse = " + CurrentQuery);
		this.ParseQuery( CurrentQuery );
	}		
	
	this.GetValue = function(key){ if(!this.ParamValues[key]) return ""; return this.ParamValues[key]; }
	this.GetAnchor = AnchorValue;

	// Output a string for display purposes
	this.OutputParams = function(){
			ShowDebug("IN this.OutputParams");
			var Params = "";
			ShowDebug("this.ParamValues = " + this.ParamValues  + " this.ParamValues.length = " + this.ParamNo>0)
			if(this.ParamValues && this.ParamNo>0){
				for(var key in this.ParamValues){
					ShowDebug("Output key " + key +" val = " + this.ParamValues[key]);
					Params+= key + ": " +  this.ParamValues[key] + "\n";
				}
			}
			if(AnchorValue!="") Params+= "Anchor: " + AnchorValue + "\n";
			ShowDebug("return " + Params);
			return Params;
		}
}

function enc(val){
	if (typeof(encodeURIComponent)=="function"){
		return encodeURIComponent(val);
	}else{
		return escape(val);
	}
}

function denc(val){
	if (typeof(decodeURIComponent)=="function"){
		return decodeURIComponent(val);
	}else{
		return unescape(val);
	}
}
