/**

' *********************************************************************
' *
' * File: CommonJS.js
' * Synopsis: commonly used Javascript functions
' *********************************************************************
' * Version   Date        By       Comment
' * -------------------------------------------------------------------
' * 2.41.7    05-10-2006  DS      added return kety protection for calendar controls year input box
' * 2.41.8    26-10-2006  DS      worked round bug introduced by AET skin where return key function can't find next button.
' * 2.43.6    15-04-2007  DS      added getMouseXY and variables to prevent javascript errors, added oActiveButton to allow processing.gif on save
' * 3.00.1	  18-04-2007  JAC	  moved addLoadEvent (from HRWorks Personnel code base)
' *********************************************************************

*/

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}



function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImgRestore() { //v3.0 
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; 
}

function MM_swapImage() { //v3.0 
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) 
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} 
} 

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_setTextOfLayer(objName,x,newText) { //v4.01
  if ((obj=MM_findObj(objName))!=null) with (obj)
    if (document.layers) {document.write(unescape(newText)); document.close();}
    else innerHTML = unescape(newText);
}

var iClickX = 0;
var IE = document.all?true:false;
var tempX = 0;
var tempY = 0;

function getMouseXY(e) {
	if (IE) { // grab the x-y pos.s if browser is IE

		tempX = event.clientX + document.body.scrollLeft;	
		tempY = event.clientY + document.body.scrollTop;	
	}
	else {  // grab the x-y pos.s if browser is NS
	tempX = e.pageX;
	tempY = e.pageY;
	}  

	if (tempX < 0){tempX = 0;}
	if (tempY < 0){tempY = 0;}  
	iClickX = tempX;
	return true;
}
var oActiveButton;

function change_style(element, newClass) {
element.className = newClass;
}

function clear_style(element) {
element.className = '';
}

function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}


// Below is from http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ 
function getElementsByClassName(oElm, strTagName, oClassNames){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}


function ie_getElementsByTagName(str) {
 // Map to the all collections
 if (str=="*")
  return document.all
 else
  return document.all.tags(str)
}

if (document.all)
 document.getElementsByTagName = ie_getElementsByTagName


function getTabCtrls() {

 var obj = document.getElementsByTagName("*")
 var tagList = "DIV;INPUT;SELECT;TEXTAREA"
 for (var i=0;i < obj.length;i++)
  if (tagList.indexOf(obj[i].tagName+";")>=0) {
    // Got One
    switch(obj[i].tagName) {
    case 'DIV': {if ((obj[i].className=='HRCB') && (obj[i].tabIndex>=0)) {AddTabObj(obj[i])};break}
    case 'INPUT': {if (obj[i].type=='text') {AddTabObj(obj[i])};break}
    case 'SELECT': {AddTabObj(obj[i]);break}
    }
  }
}

var j =0; //counter for tabbable objects
var aoTabObjs = new Array();
var HiddenElement = 0


function AddTabObj(obj) {
	//first check to see if the object is visible...
	rootobjectname = obj.name
	HiddenElement=0;
	IsHiddenElement(obj)
	if (HiddenElement==0) {
		aoTabObjs[j] = obj
		j++;
	//	alert('added [' + j + ']' + obj.name + 'tabindex' + obj.tabIndex)
	} else {
	//	alert(obj.tagName + ' was hidden')
	}
}

var rootobjectname = ''

function IsHiddenElement(obj) {
	if (obj.style.display=='none') {
		HiddenElement=1;
		return;
	}
	if (obj.parentElement!=null) {
		IsHiddenElement(obj.parentElement)
	}
	return;
}


//Emulate Tab between controls with return key and submit on last field
//nextfield = "SearchSurname"; // name of first box on page
netscape = "";
ver = navigator.appVersion; len = ver.length;
for(iln = 0; iln < len; iln++) if (ver.charAt(iln) == "(") break;
netscape = (ver.charAt(iln+1).toUpperCase() != "C");
document.onkeydown = keyDown; // work together to analyze keystrokes
if (netscape) document.captureEvents(Event.KEYDOWN|Event.KEYUP);



function keyDown(DnEvents)
{
status = ''
// determines whether Netscape or Internet Explorer

k = (netscape) ? DnEvents.which : window.event.keyCode;

if (k == 13) {
	// enter key pressed
	status = status + 'enter key pressed'


	var nextfield
	// handles keypress

	//if (aoTabObjs.length==0) {
		//i.e. do this once after load
		//er no cos things may have been hidden
		j=0;
		getTabCtrls();
	//}

	for (i = 0; i < aoTabObjs.length; i++)
		if (aoTabObjs[i]==window.event.srcElement) {
			//This is the current element - the next one in the array must be the place to send the focus.

			if (i ==aoTabObjs.length) {
			//We are at the last element cycle round to the first
				nextfield = aoTabObjs[0]
			} else {
				nextfield = aoTabObjs[i+1]
			}
		}

	//I am assuming we always have a nextfield here..





	//status = status + 'if the ctrl we are on is a button we should click it.'
	if (window.event.srcElement.className=='HRCB') {
		status = status + 'The DOM element we were on was a DIV button so click it.'
		keyDown = true;
		window.event.srcElement.click();
	}

	if (window.event.srcElement.className=='year') {
	//calendar year control
	return keyDown	
	}

	try {
	
		if (nextfield.className=='HRCB') {
			status = status + 'Next field is a button so click it'
			keyDown = true;
			status = 'submit - need to call code on div '
			nextfield.click();

		} else {
			status = status + 'we are not done yet, send focus to nextfield:' + nextfield.id
			nextfield.focus()
			if (nextfield.tagName=='INPUT') {nextfield.select();}
			keyDown = false;
		}
	} catch(error) {
		//no classname what are we doing here?
	}
} else {
	//status = 'normal key!'
	keyDown = true;
}
return keyDown
}

var dontfocus
function InitialiseDynamicCSS() {
	SizeTabParentIFrame()
	var aoDIVButs = getElementsByClassName(document, "*", 'HRCB')
	for (i = 0; i < aoDIVButs.length; i++)
	{
	//out for now because it consumes mouse down which is more important
	addEvent(aoDIVButs[i], 'focus', function() {if (this.className!='buttondown') {change_style(this, 'overbutton');}});
	addEvent(aoDIVButs[i], 'mouseover', function() {change_style(this, 'overbutton');});
	
	
	addEvent(aoDIVButs[i], 'mousedown', function() {this.focus;change_style(this, 'buttondown');});
	addEvent(aoDIVButs[i], 'mouseup', function() {this.focus;change_style(this, 'overbutton');});
	addEvent(aoDIVButs[i], 'mouseout', function() {change_style(this, 'HRCB');});
	addEvent(aoDIVButs[i], 'blur', function() {change_style(this, 'HRCB');});
	
	}
	var aoInputs = getElementsByClassName(document, 'INPUT', '*')
	for (i = 0; i < aoInputs.length; i++)
	{
	//alert(aoInputs[i].id)
	addEvent(aoInputs[i], 'mouseover', function() {if (this.className!='oncontrol'){change_style(this, 'overcontrol');}});
	addEvent(aoInputs[i], 'focus', function() {change_style(this, 'oncontrol');});
	addEvent(aoInputs[i], 'mouseout', function() {if (this.className!='oncontrol'){change_style(this, 'control');}});
	addEvent(aoInputs[i], 'blur', function() {change_style(this, 'control');});
	}
//	var aoInputs = getElementsByClassName(document, 'SELECT', '*')
//	for (i = 0; i < aoInputs.length; i++)
//	{
//	//alert(aoInputs[i].id)
//	addEvent(aoInputs[i], 'mouseover', function() {if (this.className!='oncontrol'){change_style(this, 'overcontrol');}});
//	addEvent(aoInputs[i], 'focus', function() {change_style(this, 'oncontrol');});
//	addEvent(aoInputs[i], 'mouseout', function() {if (this.className!='oncontrol'){change_style(this, 'control');}});
//	addEvent(aoInputs[i], 'blur', function() {change_style(this, 'control');});
//	}

	

}

function SizeTabParentIFrame() {
	//if we are a tabbed child this will size the iframe properly
	
		
		var oElementIFrame = window.parent.document.getElementById('tabiframe')
		
		if  (oElementIFrame!= null) {		
		
			if (IE) {
				var oTabIFrame = parent.document.frames['tabiframe']	
			} else {				
				var oTabIFrame = parent.frames[0]
			}			
			//as we are in child mode - turn off any graphics in the body style as they will probably look inapproiate within the child iframe
			oTabIFrame.document.body.style.backgroundImage = 'none'
			oTabIFrame.document.body.style.marginTop='10px'
			oTabIFrame.document.body.style.marginRight='10px'
			oTabIFrame.document.body.style.marginLeft='10px'
			oTabIFrame.document.body.style.marginBottom='10px'
			//should really set this to the same width as the parent div to start
			oElementIFrame.style.width='550px';
			oElementIFrame.style.height='100px';
			//alert(oTabIFrame.document.body.scrollHeight);
			oElementIFrame.style.width=eval(oTabIFrame.document.body.scrollWidth +20).toString() + 'px'
			//it seems that the collapsed height of the search form is not taken into account in IE6 this needs handling properly as adding 100px wont work for other search forms as they will be different sizes
			//either pick up the height of the search (and advanced)
			oElementIFrame.style.height=eval(oTabIFrame.document.body.scrollHeight +40).toString() + 'px'
		}
}


function isArrayEmpty(obj) {

//    Returns true if all the array or string arguments are empty

for (var i = 0; i < arguments.length; i++) {
    var o = arguments[i];
    if (!(o && o.length)) {
	return true;
    }
}

return false;
}

function GetRidOfPx (Ssize) {
return eval(Ssize.substring(0, Ssize.length - 2));
}

//see http://www.quirksmode.org/dom/maxlength.html for below 2 fns
function setMaxLength() {	
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>max: '+x[i].getAttribute('maxlength') + '</span>';
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = checkMaxLength;
			x[i].onchange = function () {g_blnConfirmOnUnload=true;checkMaxLength;}
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {	
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength) {
		this.className = 'toomuch';		
		this.relatedElement.style.display = 'block';
		}
	else {
		this.className = '';
		//this.relatedElement.firstChild.nodeValue = currentLength;
		this.relatedElement.style.display = 'none';
	     }
	// not innerHTML
}
