function ajaxPost(strMethod, strURL, strQuery) {
	if (strURL == '' || typeof(strURL)=='undefined')
		strURL='/uniScripts/mgrqispi.dll';

	var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open(strMethod, strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4 ) {
			updatepage(self.xmlHttpReq);
        }
    }	
    self.xmlHttpReq.send(strQuery);
}

function ajaxSend(strQuery) {
	var strURL='/uniScripts/mgrqispi.dll';
	var strMethod = 'POST'

	var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open(strMethod, strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() { return true; }	
    self.xmlHttpReq.send(strQuery);
}


function updatepage(strResponse){
	var XMLData = strResponse.responseXML.getElementsByTagName('divdata');
	var JSData = strResponse.responseXML.getElementsByTagName('parse');
	for (var x=0; x<XMLData.length; x++){
		var divid = XMLData[x].attributes.getNamedItem('divname').value;
		if (document.getElementById(divid)){
			if (navigator.appName == 'Microsoft Internet Explorer'){
				document.getElementById(divid).innerHTML = XMLData[x].firstChild.nodeValue;
			} else {
				document.getElementById(divid).innerHTML = XMLData[x].childNodes[1].nodeValue;
			}
		} else {
//			logError(5,'Data did not belong: '+divid);
		}
	}

	if (navigator.appName == 'Microsoft Internet Explorer'){
		for (var x=0; x<JSData.length; x++){
			eval(JSData[x].firstChild.nodeValue)
		}
	} else {
		for (var x=0; x<JSData.length; x++){
			eval(JSData[x].childNodes[1].nodeValue)
		}
	}

	fixPNG();
	try{ datePickerController.create(); } catch(e) { };

}

function getNodeValue(obj,tag){
	return (obj.getElementsByTagName(tag)[0].firstChild.nodeValue);
}

function create_request_string(theForm){
	var reqStr = "";
	
	for(i=0; i < theForm.elements.length; i++)	{
		isFormObject = false;
		switch (theForm.elements[i].tagName){
			case "INPUT":
			case "input":
				switch (theForm.elements[i].type){
					case "text":
					case "hidden":
					case "password":
						reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
						isFormObject = true;
						break;
				
					case "checkbox":
						if (theForm.elements[i].checked){
							reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
						}else{
							reqStr += theForm.elements[i].name + "=";
						}
						isFormObject = true;
						break;
					
					case "radio":
					if (theForm.elements[i].checked){
						reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
						isFormObject = true;
					}
				}
				break;
				
				case "TEXTAREA":
					reqStr += theForm.elements[i].name + "=" + encodeURIComponent(theForm.elements[i].value);
					isFormObject = true;
					break;
				
				case "SELECT":
					var sel = theForm.elements[i];
					reqStr += sel.name + "=" + encodeURIComponent(sel.options[sel.selectedIndex].value);
					isFormObject = true;
					break;
			}
	
		if ((isFormObject) && ((i+1)!= theForm.elements.length))
			reqStr += "&";
	}

	return reqStr;
} 

function ajaxPopUp(strMethod, strURL, strQuery, nobackground, inviewport, specialdivname, wide) {
	if (strURL == '' || typeof(strURL)=='undefined')
		strURL='/uniScripts/mgrqispi.dll';
	
	if (!nobackground)
		fadePurple(specialdivname);
		
//	showLoader();
		
	var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open(strMethod, strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            if(!wide)
				showPopup(self.xmlHttpReq.responseText, nobackground, inviewport, specialdivname);
			else
				showWidePopup(self.xmlHttpReq.responseText, nobackground, inviewport, specialdivname);			
			
			try{ datePickerController.create(); } catch(e) { };
        }
    }
    self.xmlHttpReq.send(strQuery);
}

function hideLoader(){
	if (document.getElementById('loaderdiv'))
		document.body.removeChild(document.getElementById('loaderdiv'))
}


function showMessage(message, needsconfirm){
	var DivRandNo = Math.floor(Math.random()*11);
	var messagediv = document.createElement('div');
	var divIdName = 'message_'+DivRandNo;
	
	messagediv.setAttribute('id',divIdName);
	messagediv.style.visibility = "hidden";

	document.body.appendChild(messagediv);

	if (navigator.appName == 'Microsoft Internet Explorer'){
		var p = document.getElementsByTagName('select');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
		}
		
		p = document.getElementsByTagName('object');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
			p[i].style.width = "0px";
		}
	} else {
		p = document.getElementsByTagName('embed');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
			p[i].style.width = "0px";
		}
	}

	messagetoshow = message.replace(/x1x/g,"'"+divIdName+"'")
	messagediv.innerHTML = messagetoshow;

	messagediv.style.visibility = 'visible';
	fixPNG();
	
	var scriptelements = messagediv.getElementsByTagName('script');
	for (i =0;i<scriptelements.length;i++)
		eval(scriptelements[i].innerHTML);
	
	var inputs = messagediv.getElementsByTagName('input');
//	inputs[0].focus();

	if (needsconfirm == false){
		setTimeout('hideMessage("'+divIdName+'")',5000)
	}
}

function hideMessage(DivID){
	if(document.getElementById(DivID))
		document.body.removeChild(document.getElementById(DivID));

	if (navigator.appName == 'Microsoft Internet Explorer'){
		var p = document.getElementsByTagName('select');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
		}
		
		p = document.getElementsByTagName('object');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
			p[i].style.width = "";
		}
	} else {
		p = document.getElementsByTagName('embed');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
			p[i].style.width = "";
		}
	}
}

function fixPNG(){

	var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])
	
		if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	
	
		{
		   for(var i=0; i<document.images.length; i++)
		   {
			  var img = document.images[i]
			  var imgName = img.src.toUpperCase()
			  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
			  {
				 var imgID = (img.id) ? "id='" + img.id + "' " : ""
				 var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				 var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				 var imgStyle = "display:inline-block;" + img.style.cssText 
				 if (img.align == "left") imgStyle = "float:left;" + imgStyle
				 if (img.align == "right") imgStyle = "float:right;" + imgStyle
				 if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
				 var strNewHTML = "<span " + imgID + imgClass + imgTitle
				 + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
				 + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
				 + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
				 img.outerHTML = strNewHTML
				 i = i-1
			  }
		   }
		}

}



var showEffects = false;
var showTips = true;
var isie = navigator.appName == 'Microsoft Internet Explorer';
var isie6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var onLoadQueue = new Array;
var objPCL = document.createElement('div');
var searchhasfocus = false;
var pageLoaded=false;


function doSearch(frmobj){
	if(frmobj.searchtext.value == '' || frmobj.searchtext.value == 'Document Search'){
		alert ('You must enter a search term!');
		return false;
	} else {
		var searchPath = '/uniScripts/mgrqispi.dll?APPNAME=LawLiveNZ&PRGNAME=SearchDocumentList&ARGUMENTS=-A'
		document.location.href = searchPath + frmobj.searchtext.value;
		return false;
	}
}

function onLoad(){

	try{
		Tooltip.init();
		Tooltip.followMouse = false;
	
		Tooltip.unHookHover = function () {
			var tip = document.getElementById? document.getElementById(Tooltip.tipID): null;
			if (tip) {
				tip.onmouseover = null; 
				tip.onmouseout = null;
				tip = null;
			}
		}
		
		Tooltip.tipOutCheck = function(e) {
		  e = dw_event.DOMit(e);
		  // is element moused into contained by tooltip?
		  var toEl = e.relatedTarget? e.relatedTarget: e.toElement;
		  if (document.getElementById('tipDiv') != toEl && !contained(toEl, document.getElementById('tipDiv')))
			Tooltip.hide();
		}
	
		dw_event.add(window, "unload", Tooltip.unHookHover, true);
	//	createSuggestionDiv(document.getElementById('searchfield'));
	} catch (e){
		//Yay, another do-nothing catch :)	
	}
	
	pageLoaded=true;

	runOnLoad();

}

function fadePurple(newid){
	if(typeof(newid)=='undefined')
		newid='';
	
	var pagesize = getPageSizeWithScroll();
	var windowsize = getWindowSize();
	var fadepurplebg = document.createElement('div');
	var loaderdiv = document.createElement('div');
	
	fadepurplebg.className = 'fadepurplebg';
	loaderdiv.className='loaderdiv'
	
	fadepurplebg.setAttribute('id','fadepurplebg'+newid);
	loaderdiv.setAttribute('id','loaderdiv');
	
//	loaderdiv.innerHTML='<em>Loading</em>'
	
	var divheight;
	
	if(pagesize[1]>document.body.offsetHeight)
		divheight = pagesize[1];
	else if (windowsize[1] > document.body.offsetHeight)
		divheight = windowsize[1];
	else
		divheight = document.body.offsetHeight
	
	
	fadepurplebg.style.height = divheight+'px';
	
	if (!document.getElementById('loaderdiv'))
		fadepurplebg.appendChild(loaderdiv);

	document.body.appendChild(fadepurplebg)
}

function removefadePurple(id){
	if(typeof(id)=='undefined')
		id='';
		
	if (showEffects){
		new Effect.Fade('fadepurplebg',{duration:1})
		setTimeout("document.body.removeChild(document.getElementById('fadepurplebg"+id+"'))",2001)
	} else
		document.body.removeChild(document.getElementById('fadepurplebg'+id));
}

function showWidePopup(popuptext,nobackfade,notinviewport,newdivname){
var sidecontent='<img src="/llimages/lawlive_logo.gif" width="130" height="133" alt="LawLive Logo" />';
	
	showPopup(popuptext,nobackfade,notinviewport,newdivname,sidecontent)
}

function showPopup (popuptext,nobackfade,notinviewport,newdivname,extendedcontent){	
	if(typeof(newdivname)=='undefined')
		newdivname=''

	if(typeof(extendedcontent)=='undefined')
		extendedcontent=''

	var divid = 'pop_'+Math.floor(Math.random()*5555)
	var handleid = 'hand_'+Math.floor(Math.random()*5555)
	
	while (document.getElementById(divid))
		divid = 'pop_'+Math.floor(Math.random()*5555)

	while (document.getElementById(handleid))
		handleid = 'hand_'+Math.floor(Math.random()*5555)
	
	popuptext=popuptext.replace(/x1x/g,divid);
	
	var containerdiv = document.createElement('div');
	var centrediv = document.createElement('div');
	var registration = document.createElement('div');
	var registrationbox = document.createElement('div');
	var contentcontainer = document.createElement('div');
	var containertext = document.createElement('div');

	var imgheader = document.createElement('img');
	var imgclose = document.createElement('img');
	var imgfooter = document.createElement('img');
	
	var lnkclose = document.createElement('a');
	
	if(extendedcontent != ''){
		var imgheaderwide = document.createElement('img');
		var sidecontent = document.createElement('div');
		var sidefooter = document.createElement('div');
		var sidecontainer = document.createElement('div');
	}
	

	containerdiv.className = 'popupcontainer';
	registrationbox.className = extendedcontent == ''?'registrationbox':'registrationboxwide';
	contentcontainer.className = extendedcontent == ''?'contentcontainer':'contentcontainerwide';
	containertext.className = 'containertext';
	containertext.style.zIndex='99';
	containertext.style.position='relative';
	
	containerdiv.setAttribute('id',divid);
	registration.setAttribute('id','registration');
	containertext.setAttribute('id','containertext');
	imgheader.setAttribute('id',handleid);
	
	containerdiv.style.top = notinviewport?'0px':f_scrollTop()+'px';
	
	centrediv.setAttribute('align','center');
	registrationbox.style.textAlign='left';
	
	lnkclose.setAttribute('href','#');
	
	//This is for compatibility with the oldstyle listboxes. Not sure if we still need it, but I'm not about to break something that works
	if(nobackfade)
		lnkclose.onclick =	function(){
								closePopup(divid)
								if(document.getElementById('MainDiv'))
									showFormElements(document.getElementById('MainDiv'));
								return false;
							}
	else
		lnkclose.onclick =	function(){
								closePopup(divid);
								if(document.getElementById('MainDiv'))
									showFormElements(document.getElementById('MainDiv'));
								removefadePurple(newdivname);
								return false;
							}
		
		imgheader.src = '/llimages/popup-header.png'
		imgheader.style.width = '540px';
		imgheader.style.height = '65px';

		imgclose.style.width = '90px';
		imgclose.style.height = '65px';
		imgclose.style.position = 'relative';
		imgclose.style.zIndex = '99';

	if(extendedcontent == ''){
		imgclose.src = '/llimages/popup-close-black.png'

	} else {		
		imgheader.src = '/llimages/popup-header-wide2.png'
		imgheader.style.width = '877px';

		imgclose.src = '/llimages/popup-close-wide2.png'
		
		imgheaderwide.src = '/llimages/popup-header-wide.png'
		imgheaderwide.style.width = '170px';
		imgheaderwide.style.height = '65px';
		
		sidecontent.className = 'sidecontent';
		sidecontent.innerHTML = extendedcontent;
		
		sidefooter.className = 'sidefooter';
		sidefooter.innerHTML='&nbsp;';
		
		sidecontainer.className = isie?'sidecontainer':'sidecontainerff';

		if (!isie){	//Screw you IE
			registrationbox.style.left='-175px';
		} else {
			registrationbox.style.position='relative'
			registrationbox.style.marginLeft='0px';
		}

	}
	
	if(extendedcontent == ''){
		imgfooter.src = '/llimages/popup-footer.png'
		imgfooter.style.width = '630px';
		imgfooter.style.height = '25px';
	} else {
		imgfooter.src = '/llimages/popup-footer-wide.png'
		imgfooter.style.width = '810px';
		imgfooter.style.height = '25px';
	}
	if (!isie){
		imgfooter.style.position = 'relative';
	}

	//imgfooter.style.cssFloat = 'left';

//	imgfooter.setAttribute('align','left');

	containertext.innerHTML = popuptext;
	
	lnkclose.appendChild(imgclose);

	contentcontainer.appendChild(containertext);
	registrationbox.appendChild(imgheader);
	registrationbox.appendChild(lnkclose);
	
	if(extendedcontent != '' && !isie){
		contentcontainer.style.position='absolute';

		sidecontainer.appendChild(sidecontent);
		sidecontainer.appendChild(sidefooter);
		
//		registrationbox.appendChild(imgheaderwide);
		registrationbox.appendChild(sidecontainer);
	}

	if(extendedcontent != '' && isie){
		containertext.style.zIndex='99';
		sidecontainer.style.zIndex='90';
		
		sidecontainer.appendChild(sidecontent);
		sidecontainer.appendChild(sidefooter);

//		registrationbox.appendChild(imgheaderwide);
		contentcontainer.appendChild(sidecontainer);
	}


	registrationbox.appendChild(contentcontainer);
//	registrationbox.appendChild(imgfooter);
	registration.appendChild(registrationbox);
	centrediv.appendChild(registration);
	containerdiv.appendChild(centrediv);
	
	
	//Background should already be here by now, but just in case it's not, put it there.
	if(!document.getElementById('fadepurplebg') && !nobackfade)
		fadePurple();
	
	if (document.getElementById('loaderdiv'))
		document.getElementById('fadepurplebg'+newdivname).removeChild(document.getElementById('loaderdiv'));
	
	if (showEffects){
		containerdiv.style.display = 'none';
		
		document.body.appendChild(containerdiv);
		new Effect.SlideDown(divid,{duration:1})
	} else {
		if(extendedcontent != '' && isie){
			//IE Fix, we need to hide the div, reposition it, and then put it back
			//For some reason IE and FF treat position:absolute different
			containerdiv.style.visibility='hidden';
			document.body.appendChild(containerdiv);
			contentcontainer.style.left = findPosX(document.getElementsByClassName('registrationboxwide')[0])+'px';
			contentcontainer.style.top  = (findPosY(document.getElementsByClassName('registrationboxwide')[0])+65)+'px';
			sidecontainer.style.left = findPosX(document.getElementById(handleid))+769+'px';
			if (sidecontainer.style.left != findPosX(sidecontainer)){	//Great, now we need to do a fix for IE7. Where did my life go wrong?
				var leftpos = sidecontainer.style.left;
				var difference = parseInt(leftpos.substr(0,leftpos.length-2)) - findPosX(sidecontainer);	//Difference between where it IS and where it's MEANT to be
				sidecontainer.style.marginLeft = difference+='px';		//IE7 doesn't seem to do the 'left' correctly, but changing it to a margin works just fine.
			}
				
			containerdiv.style.visibility = 'visible';
		} else {
			document.body.appendChild(containerdiv);
		}
	}
	
	if(extendedcontent != ''){
		//By now our objects have offset heights, and we need to move the footer, lest it float
		//in the wrong place.
		imgfooter.style.top=contentcontainer.offsetHeight - sidecontent.offsetHeight-35+'px';
	}

	
	hideElements();
	
	showFormElements(document.getElementById(divid));

	var scriptelements = containertext.getElementsByTagName('script');
	for (i=0;i<scriptelements.length;i++)
		eval(scriptelements[i].innerHTML);

	if(notinviewport)
		document.scrollTo(0,0);
		
	fixPNG();
	
	//Inside try as sometimes it fails for the list windows
	try {
		new Draggable(divid,{handle: handleid});
	} catch (e){
		// do nothing
	}
	
	//Stretch grey to cover screen now that the new div is there
	if(!nobackfade)
		fixStretchMarks(newdivname, divid);
//		setTimeout("fixStretchMarks('"+newdivname+"','"+divid+"')",2000);

}

function closePopup(divid){
	if (showEffects){
		new Effect.SlideUp(divid,{duration:1})
		setTimeout("document.body.removeChild(document.getElementById('"+divid+"'));",2001)
	} else
		document.body.removeChild(document.getElementById(divid));
		
	showElements();
}

function fixStretchMarks(yamum, divid){
	if(typeof(yamum)=='undefined')
		yamum='';

		
	if(document.getElementById('fadepurplebg'+yamum)){
		var pagesize = getPageSizeWithScroll();
		var windowsize = getWindowSize();
		
		if(pagesize[1]>document.body.offsetHeight)
			var divheight = pagesize[1];
		else if (windowsize[1] > document.body.offsetHeight)
			var divheight = windowsize[1];
		else
			var divheight = document.body.offsetHeight
		
		var popheight = 0;

		/*Its bad practice I know, but it IS possible for there to be more than one div
		  with the the ID containertext, however if there is it should have been created
		  without the create background flag, and thus this won't run. Anyway, this screws
		  up IE. So here's a bandaid. Dry your eyes.
		  
		  Also, I know that if this height is used (as it will in IE when the div is longer than
		  the existing page, the grey div will actually be extended past the bottom of the div by its
		  existing height. And you know what? The general consensus is that this is OK. So don't complain.
		*/
		var containers = document.getElementsByClassName('containertext');
		for (var x=0; x<containers.length; x++)
			if (containers[x].offsetHeight > popheight)
				popheight=containers[x].offsetHeight;

		if(popheight > divheight)
			divheight += popheight		//This is addition because the div doesn't sit at the top of the page and if we just added
										//then it would be too short because of the top-of-page-offset. I could fix this but the JS
										//overhead isn't worth it, and I can't be bothered.

		document.getElementById('fadepurplebg'+yamum).style.height = divheight+'px';
	}
}

function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {
		// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		// all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else {
		// works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
	}     arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	return arrayPageSizeWithScroll;
} 

function gup(name){
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var tmpURL = document.location;
	var results = regex.exec( tmpURL );
	if( results == null )
		return "";
	else
		return results[1];
}


function submitPass(frm){
	if (frm.Email.value == '')
		alert ('You must enter an email address!');
	else
		ajaxPost(strMethod, strURL, strQuery)
}

function showQuestions(status){
	var query = 'APPNAME=AIM&PRGNAME=PortalQuestionsAjax&ARGUMENTS=-N'+status
	ajaxPost('POST','', query)
}


function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return new Array(myWidth,myHeight);

}

function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

var startedUpload = false;


// Lawlive Document Generation Functions

function callcal(fname){
	var call = new calendar1(document.forms['formb'].elements[fname]);
	call.year_scroll = true;
	call.time_comp = false;
	call.popup();
}

function valbutton(radfield,radquest) {
	myOption = -1;
	for (i=0; i<radfield.length; i++) {
		if (radfield[i].checked) {
			myOption = i;
		}
	}
	if (myOption == -1) {
		alert(radquest);
		radfield[1].focus();
		return true;
	}
	else
		return false;
}

function listcallcal(frmname,fname){
	var call = new calendar1(document.forms[frmname].elements[fname]);
	call.year_scroll = true;
	call.time_comp = false;
	call.popup();
}

function valbutton(radfield,radquest) {
	myOption = -1;
	for (i=0; i<radfield.length; i++) {
		if (radfield[i].checked) {
			myOption = i;
		}
	}
	if (myOption == -1) {
		alert(radquest);
		radfield[1].focus();
		return true;
	} else
		return false;
}

function showlist(ListBox,strQuery,strDest){
//	document.getElementById('MainDiv').style.visibility = 'hidden';
	hideFormElements(document.getElementById('MainDiv'));
	showFormElements(document.getElementById(ListBox));

	//We have to do this popup manually, y'all
	fadePurple('list'+ListBox)
	showPopup(document.getElementById(ListBox).innerHTML.replace(/x2x/gi,''), false, false, 'list'+ListBox)

	if(document.formb.DocNo.value != 0 && document.getElementById(strDest)){
		document.getElementById(strDest).innerHTML = '<img src="/llimages/ajax-loader.gif"><br>Loading...';
		ajaxPost('POST','',strQuery+'&divname='+strDest);
	}
}

function helppopup(qstid, noeffect){
	var hlpdiv = document.getElementById('hlp'+qstid);
	if (hlpdiv)
		if(showEffects && !noeffect)
			Effect.Appear('hlp'+qstid,{duration:1});
		else
			hlpdiv.style.display="block";
	
	fixPNG();
}

function closeHelp(qstid, noeffect){
		if(showEffects && !noeffect)
			Effect.Fade('hlp'+qstid,{duration:1});
		else
			document.getElementById('hlp'+qstid).style.display="none";
}

function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
	return curtop;

  }
  
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }
  
	function findPos(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft
			curtop = obj.offsetTop
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
			}
		}

		return [curleft,curtop];
	}


function showHint(hint){
	var divs = document.getElementById('containertext').getElementsByTagName('div');
	for (var x=0; x<divs.length; x++)
		if(divs[x].id == 'desc-'+hint)
			if(showEffects)
				new Effect.Appear(divs[x],{duration:1})
			else
				divs[x].style.display="block";
		else
			if (divs[x].style.display != 'none')
				if(showEffects)
					new Effect.Fade(divs[x],{duration:1})
				else
					divs[x].style.display="none";
}

function tipPopup(id, text, obj, pos){
	return false;

/*
	if(!showTips)
		return false;
	
	var helpdiv = document.createElement('div');
	var bubcnt = document.createElement('div');
	var bubtop = document.createElement('div');
	var bubbot = document.createElement('div');
	var bubtxt = document.createElement('div');
	
//	bubcnt.className = 'bubble';
	bubtop.className = 'bubbletop';
	bubbot.className = 'bubblebot';
	bubtxt.className = 'bubbletxt';
	
	bubtxt.innerHTML = text;
	
	helpdiv.setAttribute('id','hlpbox'+id);
	helpdiv.style.width="150px";
	helpdiv.style.position="absolute;";
	helpdiv.style.color="#FFFFFF";

	bubcnt.appendChild(bubtop);
	bubcnt.appendChild(bubtxt);
	bubcnt.appendChild(bubbot);
	
	helpdiv.appendChild(bubcnt);
	
	//Set display to none because we need to append to body
	//before doing positioning for the innerWidth/Height

	document.body.appendChild(helpdiv);

	switch (pos){
		case 't':
			helpdiv.style.top = findPosY(obj) -  helpdiv.offsetHeight + 'px';
			helpdiv.style.left = (findPosX(obj) + (obj.offsetWidth/2 - 75)) + 'px';
			break;
		case 'b':
			helpdiv.style.top = findPosY(obj) + obj.offsetHeight + 'px';
			helpdiv.style.left = (findPosX(obj) + (obj.offsetWidth/2 - 75)) + 'px';
			break;
	}

	fixPNG();
*/
}

function tipHide(id){
	return false;
	/*
	document.body.removeChild(document.getElementById('hlpbox'+id));
	*/
}

function savedets(template){
	document.formb.DocParam.value = template?"T":"S"
	document.formb.submit();
}

function affixDocJS(doccode){
	var scr = document.createElement('script');
	scr.src = '/DocJS/'+doccode;
	document.body.appendChild(scr);
}

function submitFormList(frmobj, div, frm){
	document.getElementById(div).innerHTML = '<img src="/llimages/ajax-loader.gif"><br>Loading...';
	
	if(document.formb.DocNo.value == 0){
		document.formb.DocParam.value = "S";
		document.formb.Ajaxed.value = 'Y';
		ajaxPost('POST',document.formb.action,create_request_string(document.formb)+'fromlist=Y&command=submitFormList(document.'+frm+',"'+div+'","'+frm+'")','');
		document.formb.Ajaxed.value = 'N';
	} else {
		frmobj.DocNo.value = document.formb.DocNo.value;
		ajaxPost('POST','',create_request_string(frmobj)+'&formname='+frm+'&divname='+div);
	}
	
}

function forgotPassword(){
	ajaxPopUp('GET','/forgotpass.html','');	
}

function subForgotPass(email, ff){

	var suffix = ff?'Y':'N'
	var query = 'APPNAME=LawLiveNZ&PRGNAME=ForgotLoginDetails&ARGUMENTS=-A'+email+',-A'+suffix;

	ajaxPost('POST','',query);
}

function hideFormElements(div){
	var tds = div.getElementsByTagName('select');
	for (var x=0; x<tds.length; x++)
		tds[x].style.visibility = 'hidden';
	
	var tds = div.getElementsByTagName('input');
	for (var x=0; x<tds.length; x++)
		if (tds[x].getAttribute('type')!='hidden')
			tds[x].disabled = true;

	var tds = div.getElementsByTagName('textarea');
	for (var x=0; x<tds.length; x++)
		tds[x].disabled = true;

}

function showFormElements(div){
	var tds
	tds = div.getElementsByTagName('select');
	for (var x=0; x<tds.length; x++)
		tds[x].style.visibility = 'visible';
	
	tds = div.getElementsByTagName('input');
	for (var x=0; x<tds.length; x++)
		tds[x].disabled = false;

	tds = div.getElementsByTagName('textarea');
	for (var x=0; x<tds.length; x++)
		tds[x].disabled = false;

	tds = div.getElementsByTagName('object');
	for (var x=0; x<tds.length; x++){
		tds[x].style.visibility = "visible";
		tds[x].style.width = "";
	}

	tds = div.getElementsByTagName('embed');
	for (var x=0; x<tds.length; x++){
		tds[x].style.visibility = "visible";
		tds[x].style.width = "";
	}
}

function clearSearch(obj){
	searchhasfocus = true;
	
	if(obj.value ==	 'Document Search')
		obj.value = '';
		
	//If there is already a value in there, re-run the suggester
	if (obj.value.length >= 3)
		checkPCList(obj.value);
}

function restoreSearch(obj){
	searchhasfocus = false;
	
	if(obj.value ==	 '')
		obj.value = 'Document Search';
	
	//Hide search div
	setTimeout('hideDiv()',500);
}

function updateDocsInProgress(){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=docsInProgress';
	ajaxPost('POST','',query);
}

	function SetCookie(name,value,expires,path,domain,secure){
		// set time, it's in milliseconds
		var today = new Date();
		today.setTime( today.getTime() );
		
		/*
		if the expires variable is set, make the correct 
		expires time, the current script below will set 
		it for x number of days, to make it for hours, 
		delete * 24, for minutes, delete * 60 * 24
		*/
		if ( expires ){
			expires = expires * 1000 * 60 * 60 * 24;
		}
		
		var expires_date = new Date( today.getTime() + (expires) );
		
		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
	
	function GetCookie(name) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) &&
		( name != document.cookie.substring( 0, name.length ) ) )
		{
		return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ";", len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
	}
	
	function DeleteCookie(name, path, domain ) {
		if ( Get_Cookie( name ) ) document.cookie = name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}

function addEmailAddresses(){
	ajaxPopUp('GET','/addemails.html','');			
}

function getAddEmails(){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=dispEmailAddress';
	ajaxPost('POST','', query)	
}

function delAddEmail(emailadd){
	if(confirm('Are you sure you want to remove the email address:\n\n'+emailadd+'?')){
		var query = 'APPNAME=LawLiveNZ&PRGNAME=delEmailAddress&ARGUMENTS=-A'+emailadd;
		ajaxPost('POST','', query)	
		document.getElementById('addemailnote').innerHTML = '<em>Deleting...</em>';

	}
}

function addEmail(frm){
	if (frm.addname.value == ''){
		alert ('You must enter a name for this person');
		frm.addname.focus();
		return false;
	} else if (frm.addemail.value == ''){
		alert ('You must enter an email address for this person');
		frm.addemail.focus();
		return false;
	} else {
		document.getElementById('addemailnote').innerHTML = '<em>Adding...</em>';
		ajaxPost('POST','', create_request_string(frm));
		frm.reset();
		return false;
	}
}

function showSubComp(){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=subscriptioncomparison';
	ajaxPopUp('POST','', query)	
}

function hideElements(){
	if (navigator.appName == 'Microsoft Internet Explorer'){
		var p = document.getElementsByTagName('select');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
		}
		
		p = document.getElementsByTagName('object');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
			p[i].style.width = "0px";
		}
	} else {
		p = document.getElementsByTagName('embed');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "hidden";
			p[i].style.width = "0px";
		}
	}	
}

function showElements(){
	if (navigator.appName == 'Microsoft Internet Explorer'){
		var p = document.getElementsByTagName('select');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
		}
		
		p = document.getElementsByTagName('object');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
			p[i].style.width = "";
		}
	} else {
		p = document.getElementsByTagName('embed');
		for(i=0;i<p.length;i++) {
			p[i].style.visibility = "visible";
			p[i].style.width = "";
		}
	}
}

//Tooltip Functions



// returns true of oNode is contained by oCont (container)
function contained(oNode, oCont) {
  if (!oNode)
  	return; // in case alt-tab away while hovering (prevent error)
		
	while ( oNode = oNode.parentNode )
		if ( oNode == oCont )
			return true;
  return false;
}

function hideStaticTip() {
  if ( typeof Tooltip == "undefined" || !Tooltip.ready ) return;
  Tooltip.timerId = setTimeout("Tooltip.hide()", 300);
}


// Scrolling Functions

//Manual Scroller- © Dynamic Drive 2001
//For full source code, visit http://www.dynamicdrive.com

function movedown(){
	if (window.moveupvar) clearTimeout(moveupvar)
	if (iens6&&parseInt(crossobj.style.top)>=(contentheight*(-1)+100))
	crossobj.style.top=parseInt(crossobj.style.top)-speed+"px"
	else if (ns4&&crossobj.top>=(contentheight*(-1)+100))
	crossobj.top-=speed
	movedownvar=setTimeout("movedown()",20)
}

function moveup(){
	if (window.movedownvar) clearTimeout(movedownvar)
	if (iens6&&parseInt(crossobj.style.top)<=0)
	crossobj.style.top=parseInt(crossobj.style.top)+speed+"px"
	else if (ns4&&crossobj.top<=0)
	crossobj.top+=speed
	moveupvar=setTimeout("moveup()",20)
}

function stopscroll(){
	if (window.moveupvar) clearTimeout(moveupvar)
	if (window.movedownvar) clearTimeout(movedownvar)
}

function movetop(){
	stopscroll()
	if (iens6)
		crossobj.style.top=0+"px"
	else if (ns4)
		crossobj.top=0
}

function getcontent_height(){
	if (iens6)
		contentheight=crossobj.offsetHeight
	else if (ns4)
		document.nsnavcontainer.document.nscontent.visibility="show"
}

var speed=5

iens6=document.all||document.getElementById
ns4=document.layers

var crossobj
var contentheight

function setCrossObj(){
	crossobj=document.getElementById? document.getElementById("navcontent") : document.all.content
	contentheight=crossobj.offsetHeight	
}

function showExtendedNav(e, obj, title, contentdiv, dontexpand){
	var defArrowTop = 20	//The number of pixles the TOP of the arrow box should be from the top of the container

	//Overload
	if(typeof(dontexpand)=='undefined')
		dontexpand=false;


	var offx = menuBoundX(obj)

	var menuYBounds = menuBoundY(obj, defArrowTop);

	var offy = menuYBounds[0];
	var arrowTop = menuYBounds[1];
	
//	Tooltip.show(e, makeExtNav(title,document.getElementById(contentdiv+'_desc').innerHTML,document.getElementById(contentdiv+'_docs').innerHTML, arrowTop, dontexpand), offx, offy);
	Tooltip.show(e, makeExtNav(title,'',document.getElementById(contentdiv+'_docs').innerHTML, arrowTop, dontexpand), offx, offy);
	
	//Now that we've made the div & displayed it we need to adjust the height of the div to fit all the contents if the content
	//is more than 300px high
	if(document.getElementById('navcontent') && document.getElementById(contentdiv+'_list')){
		var ulobj = document.getElementById(contentdiv+'_list');
		var liobj = ulobj.getElementsByTagName('li');
		var divheight=0
		for (var x=0;x<liobj.length;x++)
			divheight += liobj[x].offsetHeight;
		
		if(divheight>300)
			document.getElementById('navcontent').style.height = divheight +'px';
	}
	
	if (dontexpand)
		document.getElementById('mouseoverhandle').style.width='30px';

	setCrossObj();

}

function makeExtNav(title,desc,thiscontent,arrowoffset){
	
	var content ='<div id="mouseoverhandle"><img src="/llimages/spacer.gif" style="width:100%; height:100%" /></div><div id="extendednav" onMouseOut="Tooltip.tipOutCheck(event)"><div id="extendednavarrow" style="margin-top:'+(arrowoffset-15)+'px;"></div><div id="extendednavcontainer"><div id="extendednavtop"><h6>'
	content += title;
	content += '</h6></div><div id="extendednavup"><a href="#" onMouseOver="javascript:moveup()" onMouseOut="javascript:stopscroll()"><img src="/llimages/extendednav-up.gif" height="10" width="210" alt="LawLive" border="0"></a></div>';
	content += '<div id="extendednavcontent">'

/*
	var content = '<div id="mouseoverhandle"><img src="/llimages/spacer.gif" style="width:100%; height:100%" /></div><div id="extendednav" onMouseOut="Tooltip.tipOutCheck(event)"><div id="extendednavarrow" style="margin-top:'+(arrowoffset-15)+'px;"></div><div id="extendednavcontainer"><div id="extendednavtop"><h6>'+title+'</h6></div><div id="extendednavup"><a href="#" onMouseOver="javascript:moveup()" onMouseOut="javascript:stopscroll()"><img src="/llimages/extendednav-up.gif" height="10" width="210" alt="LawLive" border="0"></a></div><div id="extendednavcontent"><div id="extendednavintro">'
	content += desc;
*/
	content += '<div id="navcontainer" style="position:relative; left: 10px; width:440px; height: 300px; overflow:hidden; color:#ffffff; "><div id="navcontent" style="position:absolute; height: inherit; width:440px;left:0px;top:0px;"><ilayer name="nsnavcontainer" width=155 height=160 clip="0,0,155,160"><layer name="nscontent" width=155 height=160 visibility=hidden>';
	content += thiscontent;
	content += '</layer></ilayer></div></div></div><div id="extendednavup"><br><a href="#" onMouseOver="javascript:movedown()" onMouseOut="javascript:stopscroll()" style="position:relative; z-index:1000;"><img src="/llimages/extendednav-down.gif" height="10" width="210" alt="LawLive" border="0"></a></div><div id="extendednavbottom"><br></div></div></div>';

	return content;
}

function menuBoundX(obj){
	var objx = findPosX(obj);		//Left of the object
	var objwidth = obj.offsetWidth;	//Total width of object
	return objx+objwidth-3;			//Minus three so we can mouse from one box to the other without closing the div
}

function menuBoundY(obj, arr){
	//Accepts the object & ideal top of arrow box, returns the top of the box and the top of the arrow box position
	viewport.getAll();			//Initalise viewport object
	var objy = findPosY(obj)	//Top of the object
	var objheight = obj.offsetHeight 	//Total height of the document
	var arrowpoint= objy + objheight/2	//This is where the arrow needs to point to
	
	if(objy+objheight+470>viewport.height+viewport.scrollY)	//Box is 460px but needs 10px at bottom to make it look nice. See if it fits. If it doesn't fix, we will need to adjust the box and the position of the arrow
		var divTop = viewport.height+viewport.scrollY-470;	//Put the top of the box 470px from the bottom of the viewport
	else
		var divTop = objy-arr-15; 	//The middle of the arrow is (arrow) pixles from top of the box, thus we know where to line the fucker up to	
	
	//Ok, we know where the top of the DIV is GOING to be, and where the arrow NEEDS to be.
	var arrTop=(arrowpoint-divTop);
	
	return new Array(divTop,arrTop)
}

function askConfirm(UpdPurDocM,frmobj){
	var UpPur=UpdPurDocM?'yes':'no';
	var query = 'APPNAME=LawLiveNZ&PRGNAME=PromptConfirmation&ARGUMENTS=-A'+UpdPurDocM+',-A'+frmobj;
	ajaxPopUp('POST','', query, false, false, 'conf');
}

function doConfirm(frmobj){
	var newurl='/uniScripts/mgrqispi.dll';
	if (document.location.href.indexOf('localhost') == -1 && document.location.href.indexOf('unitest') == -1 &&  document.location.href.indexOf('127.0.0.1') == -1)
		if (document.location.protocol == 'http:')
			var newurl = 'https://lawlive.co.nz/uniScripts/mgrqispi.dll';

	with (frmobj){
		action = newurl;
		//Confirm.disabled = true;
		submit();
	}

//	alert (create_request_string(frmobj))
}

//These functions are disabled for IE as it does not seem to allow
//the modification of a password field type
function setPasswordField(obj){
	if (navigator.appName != 'Microsoft Internet Explorer')
		if(obj.value == ''){
			obj.value = 'Password';
			obj.setAttribute('type','text');
		}
}

function unsetPasswordField(obj){
	if (navigator.appName != 'Microsoft Internet Explorer'){
		obj.setAttribute('type','password');
		if(obj.value == 'Password'){
			obj.value = '';
	
		}
	}
}

function setUsernameField(obj){
	if(obj.value == '')
		obj.value = 'Email/Username';
}

function unsetUsernameField(obj){
	if(obj.value == 'Email/Username'){
		obj.value = '';
	}
}

function catRollover(divid,islast){
	var obj = document.getElementById(divid);
	var currclass = obj.className
	var isHigh = currclass == 'statboxclick' || currclass == 'statboxrightclick';
	if (!isHigh)
		obj.className = islast?'statboxrightroll':'statboxroll'
}

function catRollout(divid,islast){
	var obj = document.getElementById(divid);
	var currclass = obj.className
	var isHigh = currclass == 'statboxclick' || currclass == 'statboxrightclick';
	if (!isHigh)
		obj.className = islast?'statboxright':'statbox'
}

function catClick(divid,islast){
	var objs = document.getElementsByClassName('statboxclick');
	for (var x=0; x < objs.length; x++)
		objs[x].className=objs[x].className='statbox'


	objs = document.getElementsByClassName('statboxrightclick');
	for (var x=0; x < objs.length; x++)
		objs[x].className=objs[x].className='statboxright'
	
	var obj = document.getElementById(divid);
		obj.className = islast?'statboxrightclick':'statboxclick'
}

function execOnLoad(command){
	onLoadQueue.push(command);	
}

function runOnLoad(){
	//Check to see if we need to popup about an expired subscription
	if (gup('exp')=='Y')
		ajaxPopUp('POST','','APPNAME=LawLiveNZ&PRGNAME=ExpiredSubscription');

	for (var x=0;x<onLoadQueue.length;x++)
		onLoadQueue[x]();
}

function showMenuLoad(){
	var loader='<div style="text-align:center"><img src="/llimages/ajax-loader2.gif"><br><strong>Loading Menu</strong></div>';
	document.getElementById('glassbuttons').innerHTML=loader;
}


function createSuggestionDiv(obj){
	with (objPCL){
		setAttribute('id','objPCL');
		style.width = '300px';
		style.height = '300px';
		style.visibility = 'hidden';
	}
	document.getElementById('suggestioncontainer').appendChild(objPCL);
	
	
	//Some dicky IE6 fix here. The CSS is desgined for IE6 (its easier to add changes than remove them). Man I wish this
	//wasn't nessesary.
	if (!isie6){
		document.getElementById('suggestioncontainer').style.top='8px';
		document.getElementById('suggestioncontainer').style.position='relative';
	}
	
	hideDiv();
	
//	document.getElementById('PCList').style.display='none';
}

function destroyDiv(){
	if (document.getElementById('objPCL'))
		document.body.removeChild(document.getElementById('objPCL'));
}

function hideDiv(){
	if (document.getElementById('objPCL')){
		document.getElementById('objPCL').style.height='0px';
		document.getElementById('objPCL').style.visibility='hidden';
		document.getElementById('objPCL').style.zIndex='0';
	}
}

function checkPCList(postcode){
	//Ok, only continue if we know the div exists and they've typed three characters
	if(document.getElementById('objPCL'))
		if(postcode.length >= 3 && searchhasfocus){
			document.getElementById('searchloader').style.display = 'inline';
			var querystring = 'APPNAME=LawLiveNZ&PRGNAME=SearchSuggestionsXML&ARGUMENTS=-A'+postcode;
			ajaxPost('POST', '', querystring);
		} else {
			hideDiv();
		}	
}

function fixSuggestionDiv(){

	if (document.getElementById('PCList')){
		if(!searchhasfocus)
			hideDiv();
		else {
			var objPCList = document.getElementById('PCList')
	
			var txtheight = objPCList.offsetHeight;
		
			//If the offsetheight returns 0, then we need to calculate them all
			//the A heights individually
/*			if (txtheight == 0){
				var aels=objPCList.getElementsByTagName('a');
				txtheight = (aels.length+1)*13;
			}
*/
			var divheight = '';
			var divwidth = 200;
//			if(txtheight > 160)
//				divheight = '160px'
//			else
				divheight = txtheight+'px';
	
			var as = objPCList.getElementsByTagName('a')
	
			for (var x=0; x<as.length;x++)
				if(as[x].offsetWidth > divwidth)
					divwidth=as[x].offsetWidth;
	

			with(document.getElementById('objPCL')){
				style.display = 'block';    
				style.visibility='visible'
				style.height = divheight;
				style.width = divwidth+50+'px';
				style.zIndex='99'
			}
		
			document.getElementById('PCList').style.display='block';
		}
	}

}

function fixPCLPos(){
	
	//not Used

}

function showLoginRedirect(r){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=redirloginpage&ARGUMENTS=-A'+r
	ajaxPopUp('POST','', query)
}

function fixFormFooter(){
	//Get footer
	var imgfooter;
	var contentcontainer;
	var sidecontent;
	var images = document.getElementsByTagName('img');
	for (var x=0;x<images.length;x++)
		if (images[x].src.indexOf('popup-footer.png') >= 0){
			try{
				contentcontainer = images[x].parentNode.getElementsByClassName('containertext')[0];
				sidecontent = images[x].parentNode.getElementsByClassName(isie?'sidecontainer':'sidecontainerff')[0] 	
				images[x].style.top=contentcontainer.offsetHeight - sidecontent.offsetHeight+'px';	
				alert ('asdf')
			} catch(e) {
				//Whoops	
			}
		}
}

function trim(str){
	return str.replace(/^\s+|\s+$/g, '') ;	
}

function chkFormVal(frmObj){
	//Skip validation of hidden, checkbox, password, submit, and a few others, as there is no point in validating these
	//Return false if the input question is OK, return true if we need to display an error message
	try {
		var objName = frmObj.getAttribute('name');
		var isBlank = true;
		var isVisible = document.getElementById('D'+objName).style.display != 'none';
		
		if (!isVisible){
			return false;
		} else	{
			switch (frmObj.tagName.toLowerCase()){
				case 'input':
					switch (frmObj.getAttribute('type').toLowerCase()){
						case 'text':
							return frmObj.value.length == 0;
							break;
						case 'button':
							return document.getElementById('LC'+objName).value == '0'
							break;
							
						case 'radio':
							if (frmObj.length > 0)
								for (var x=0;x<frmObj.length;x++)
									if (frmObj[x].checked)
										return false;

							return true;
							break;

						default:
							return false;
							break;
					}
					
					break;
				
				case 'textarea':
					return frmObj.value.length == 0;
					break;
				
				case 'select':
					return frmObj[frmObj.selectedIndex].value == "";
					break;
					
				default:
					return false;
					break;
			}
		}
	} catch (e){
		//For some reason sometimes radio buttons fail, so we will catch them here
		if (frmObj.length > 0){
			//Check if object is hidden
			if(document.getElementById('D'+frmObj[0].getAttribute('name')).style.display == 'none')
				return false;
			
			//Run through all node values
			for (var x=0;x<frmObj.length;x++)
				if (frmObj[x].checked)
					return false;
					
			return true;
		
		} else 
			return false;
	}
}

function getTestimonial(){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=ViewTestimonialsAjax'
	if (typeof(document.getElementById('testimonialsbox'))!='undefined')
		ajaxPost('POST','', query)
}

function toggleCat(cat,linkobj){
	var divobj = document.getElementById('cats'+cat);
	var conobj = document.getElementById('catlist');
	if (divobj){
		if (divobj.style.display=='none'){
			//We need to close all the other divs
			var divs = conobj.getElementsByTagName('div')
			for (var x = 0; x<divs.length;x++)
				if (divs[x].id.indexOf('cats')>-1 && divs[x].style.display!='none')
					Effect.SlideUp(divs[x].id,{duration:.5})
					
			new Effect.SlideDown('cats'+cat,{duration:.5})	
		}
		else 
			new Effect.SlideUp('cats'+cat,{duration:.5})
	}
}

function saveTemp(docid,duplicate){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=saveTempName&ARGUMENTS=-N'+docid+',-A'+duplicate;
	ajaxPopUp('POST','', query, false, false, 'savetemplate', false)	
//	ajaxPopUp('GET','', '/forgotpass.html')	
}

function saveAsTemplate(tempname,duplicate,docid){
	if (tempname == ''){
		alert ('Template name cannot be blank');
		return false;
	} else {
		if (!duplicate){
			document.formb.TempName.value = tempname;
			savedets(true);
		} else {
			if (document.templateDupSave)
				with (document.templateDupSave){
					docid.value = docid
					tempname.value = tempname
					submit();
				}
		}
	}
}

function cap(obj){
/*
try {
		if (obj.value != ''){
			var frmObj = document.formb;
			var docNo = frmObj.DocNo.value;
			var docCode = frmObj.ARGUMENTS.value.split(',')[1].substr(2)
			var fieldName = obj.getAttribute('name');
			var fieldVal = encodeURI(obj.value);
			
			var query = 'APPNAME=LawLiveNZ&PRGNAME=LogBuildProgress&ARGUMENTS=-N'+docNo+',-A'+docCode+',-A'+fieldName+',-A'+fieldVal
			ajaxSend (query);
		}
	} catch (e){ 
		return false;
	}
*/
	return true;
}

function setFeedback(p){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=ViewStarFeedback&ARGUMENTS=-N'+p;
	ajaxPost ('POST','',query);
}

function submitStarFeedback(p){
	var feedText = document.getElementById('txtFeedback'+p).value;
	feedText = feedText.replace(',','|');
	feedText = encodeURIComponent(feedText);

	var query = 'APPNAME=LawLiveNZ&PRGNAME=SubmitRating&ARGUMENTS=-N'+p+',-N,-A'+feedText;
	ajaxPost ('POST','',query);
	closeHelp('Feedback'+p)
}

	function showPane(tab){
		if (tab == 'old'){
			document.getElementById('imgold').src = '/llimages/tab-new-off.gif'
			document.getElementById('imgnew').src = '/llimages/tab-existing-on.gif'
			
			document.getElementById('divold').style.display='block';
			document.getElementById('divnew').style.display='none';
		} else {
			document.getElementById('imgold').src = '/llimages/tab-new-on.gif'
			document.getElementById('imgnew').src = '/llimages/tab-existing-off.gif'

			document.getElementById('divnew').style.display='block';
			document.getElementById('divold').style.display='none';

		}
	}

function toggleDivVisibility(divid){
	if (document.getElementById(divid).style.display=='none'){
		Effect.SlideDown(divid, { duration: 1.0 });
	} else {
		Effect.SlideUp(divid, { duration: 1.0 });
	}
}

function useDoc(docID,divId){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=saveDocAsTemplate&ARGUMENTS=-N'+docID+'&DivID='+divId
	ajaxPost ('POST','',query)
	document.getElementById('butold'+docID).src = "/llimages/ajax-loader4.gif"
}

function newDoc(docCode,divId){
	var query = 'APPNAME=LawLiveNZ&PRGNAME=createDocAsTemplate&ARGUMENTS=-A'+docCode+'&DivID='+divId
	ajaxPost ('POST','',query)
	document.getElementById('butnew'+docCode).src = "/llimages/ajax-loader4.gif"
}

function setupListAddButtions(){
	var tables = document.getElementsByTagName('table');
	var listtables = new Array()
	var prefix = 'TBL'
	var x, y, z, thisnum = 0
	
	for (x = 0;x<tables.length; x++)
		if (tables[x].id.substring(0,3) == prefix)
			listtables.push(tables[x])

	listtables.sort(function(a,b){return findPosY(a) - findPosY(b);})

	for (y = 0; y < listtables.length; y++){
		suffix = listtables[y].id.substr(listtables[y].id.length - 2,2);
		
		if (isNaN(suffix))
			return false;
			
		var butobj = document.getElementById('BUTADD'+listtables[y].id.replace('TBL',''))
		
		//Add the 'Add Another' link to the last item
//		if(y==(listtables.length-1) || typeof(listtables[y+1])!='undefined')
			if (y==(listtables.length-1) || listtables[y].id.substr(0,listtables[y+0].id.length-2) != listtables[y+1].id.substr(0,listtables[y+1].id.length-2)){	//Check if this is the last item, OR if this item and the NEXT item are completely different, then this is the last item in that list.
				thisnum = parseInt(listtables[y].id.substr(listtables[y].id.length-2,2),10);
				butobj.innerHTML='<img src="/llimages/add.png" width="16" height="16" align="Add another item" /><em><a href="#" onclick="addListItem(\''+listtables[y].id+'\',\''+PadDigits(thisnum+1,2)+'\'); return false;">Add another</a></em>'
			} else
				butobj.innerHTML=''
	}
	
	
}

function setupLists(){
	//This finds all the ListBox items on the page, turns them into copiable templates, and gives them all unique names
	var listtables = new Array()
	var prefix = 'TBL'
	var tables = document.getElementsByTagName('table');
	var listitemstemp = new Array();
	var listitems = new Array();
	var x, y, z = 0
	var suffix = '';
	
	for (x = 0;x<tables.length; x++)
		if (tables[x].id.substring(0,3) == prefix)
			listtables.push(tables[x])

	for (y = 0; y < listtables.length; y++){
		suffix = listtables[y].id.substr(listtables[y].id.length - 2,2);
		
		if (isNaN(suffix))
			return false;

		//Add input fields
		listitemstemp = listtables[y].getElementsByTagName('input');
		for (z = 0; z < listitemstemp.length; z++)
			listitems.push(listitemstemp[z])

		//Add select fields
		listitemstemp = listtables[y].getElementsByTagName('select');
		for (z = 0; z < listitemstemp.length; z++)
			listitems.push(listitemstemp[z])

		//Add textarea fields
		listitemstemp = listtables[y].getElementsByTagName('textarea');
		for (z = 0; z < listitemstemp.length; z++)
			listitems.push(listitemstemp[z])
		
		//Add the suffix field onto the field items		
		for (x = 0; x < listitems.length; x++)
			if (listitems[x].name.substr(listitems[x].name.length-2,2) != suffix)
				listitems[x].name += suffix;

		listitems.length = 0;
	}
	
	setupListAddButtions();
	fixFormFooter();
	setupTabOrders();
}

function setupTabOrders(){
	//The tab order script used to work just fine, but now that the listboxes are merged into the document AFTER the tab orders have been written, it's all broken
	//so we need to go through and re-tab all the items. And even if we could include the tab order during the last merge, they're merged out of order anyway, so it would
	//still be no good. So go forth my minions and fix!
	
	var frmObj = document.formb;
	var frmitemstemp = new Array();
	var frmitems = new Array();
	var x,z,c = 0;
	var oldonclick;

	frmitemstemp = frmObj.getElementsByTagName('input');
	for (z = 0; z < frmitemstemp.length; z++)
		frmitems.push(frmitemstemp[z])

	//Add select fields
	frmitemstemp = frmObj.getElementsByTagName('select');
	for (z = 0; z < frmitemstemp.length; z++)
		frmitems.push(frmitemstemp[z])

	//Add textarea fields
	frmitemstemp = frmObj.getElementsByTagName('textarea');
	for (z = 0; z < frmitemstemp.length; z++)
		frmitems.push(frmitemstemp[z])

	//At the moment the elements are all out of order, so we need to order them appropriately
	//which is by vertical position. This is o(2^slow) but I don't have a compsci degree, so this
	//is me not caring.
	frmitems.sort(function(a,b){return findPosY(a) - findPosY(b);});

	for (x = 0;x<frmitems.length;x++){
		if (!isNaN(frmitems[x].getAttribute('tabindex'))){
			c++;
			frmitems[x].setAttribute('tabindex',c);
		}
	}
}

function removeListItem(itemcode,itemid){
	var ok = 0;
	//Need to check if this is the last list element on the page
	var tables = document.getElementsByTagName('table');
	
	for (var x = 0; x < tables.length; x++)
		if (tables[x].id && tables[x].id.indexOf(itemcode)>-1)
			ok++
	
	if(confirm('Are you sure you want to remove this item from your document?')){
		if (ok==1)	//If this is the last item, then create a new blank one to replace it
			addListItem('TBL'+itemcode+itemid,itemid)

		var obj = document.getElementById('TBL'+itemcode+itemid);
		obj.parentNode.removeChild(obj);
//		obj.innerHTML=''
//		obj.style.display='none';
//		obj.id = '';
   }

	setupListAddButtions();
	fixFormFooter();
	setupTabOrders();

}

function addListItem(itemcode,itemid){
	var obj = document.getElementById(itemcode).cloneNode(true);
	var intid = parseInt(itemid,10)
	var listitems = new Array();
	var thisobj, temp, z, y, x;
	var paddedid = PadDigits(intid+1,2)
	
	temp = obj.getElementsByTagName('input');
		for (z = 0; z < temp.length; z++)
			listitems.push(temp[z])
	temp = obj.getElementsByTagName('textarea');
		for (z = 0; z < temp.length; z++)
			listitems.push(temp[z])
	temp = obj.getElementsByTagName('select');
		for (z = 0; z < temp.length; z++)
			listitems.push(temp[z])
	temp = obj.getElementsByTagName('div');
		for (z = 0; z < temp.length; z++)
			listitems.push(temp[z])

	//Set the ID
	obj.id = itemcode.substr(0,itemcode.length-2)+paddedid
	var shortid = obj.id.substr(3,obj.id.length-5)

	for (x=0;x<listitems.length;x++){
		thisobj = listitems[x]

		if (typeof(thisobj)=='select')
			thisobj.selectedIndex=0;
		else if (typeof(thisobj)!='div')
			thisobj.value=''

		if (thisobj.name)							//If this is not a DIV
			thisobj.id = thisobj.name = thisobj.name.substr(0,thisobj.name.length-2) + paddedid
		else {	//If this is a DIV	
			thisobj.id = thisobj.id.substr(0,thisobj.id.length-2) + paddedid	//Increase the counter on the DIV (if the div doesn't have a counter, we'll be ruining the element ID, but this is no big deal as if it doesn't have a number hten it's not referenced anywhere anyway,

			if(thisobj.id.substr(0,6)=='BUTADD')	//If this is the Add button
				thisobj.innerHTML = '<img src="/llimages/add.png" width="16" height="16" align="Add another item" /><em><a href="#" onclick="addListItem(\''+obj.id+'\',\''+paddedid+'\'); return false;">Add another</a></em>'
			if(thisobj.id.substr(0,6)=='BUTREM')	//If this is the Remove button
				thisobj.innerHTML = '<img src="/llimages/stop.png" align="Remove this item" height="16" width="16"><em><a href="#" onclick="removeListItem(\''+shortid+'\',\''+paddedid+'\'); return false;">Remove</a></em>'
		}
	}

	
	insertAfter(obj,document.getElementById(itemcode));

	//Wipe out the "Add Another" link to existing node
	document.getElementById('BUTADD'+itemcode.replace('TBL','')).innerHTML = ''
	
//	setupListAddButtions();
	fixFormFooter();
	setupTabOrders();
}


function PadDigits(n, totalDigits){ 
	  n = n.toString(); 
	  var pd = ''; 
	  if (totalDigits > n.length)
		  for (i=0; i < (totalDigits-n.length); i++) 
			  pd += '0'; 
	  return pd + n.toString(); 
}
  
function insertAfter(newChild, refChild) { 
	refChild.parentNode.insertBefore(newChild,refChild.nextSibling); 
} 

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_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_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_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 stayHere(divid){
	SetCookie('countrychecked','Y')
	closePopup(divid);
	if(document.getElementById('MainDiv'))
		showFormElements(document.getElementById('MainDiv'));
	removefadePurple('');
}
