//<![CDATA[
 
function $(aId){return document.getElementById(aId);}

gUtils={};

gUtils.popupWindow=function(aUrl,aName,aBasic,aHeight,$aWidth)
{
	var w;
	if ($aWidth)
		w=$aWidth
	else 
		w=aBasic ? 180 : 600;
	var h=aBasic ? 130 : 605;
	if (aHeight)
		h=aHeight;
	var l=(screen.width-w)/2;
	var t=(screen.height-100-h)/2;

	var newWindow = window.open(aUrl,aName,'width='+w+',height='+h+',top='+t+',left='+l+',resizable=0,location=0,scrollbars=0,toolbar=0,status=0');
	newWindow.focus();
	return false;
};

/****************************************************************
	Submit - after updating a form's action
*/


gUtils.mouseOver=function(aDivId)
{
	var img=$(aDivId+"_img");
	if (img)
		img.src=img.src.replace(/\.gif$/,"Over.gif");
}

gUtils.mouseOut=function(aDivId)
{
	var img=$(aDivId+"_img");
	if (img)
		img.src=img.src.replace(/Over\.gif$/,".gif");
}

// no path in the image src (assumes the same directory)
gUtils.setImageSrc=function(aImageId,aSrc)
{
	$(aImageId).src=$(aImageId).src.replace(/[^\\^\/]*\.gif$/,aSrc);
}

gUtils.formatDate=function(aDate)
{
	var dateElements=aDate.split(" ");
	var dateDigit=dateElements[2]%10;
	var dateTen=Math.floor(dateElements[2]/10);
	var abbr="th";
	if (dateTen!=1)	// between 10 & 19
	{
		switch (dateDigit)
		{
		case 1:
			abbr="st";
			break;
		case 2:
			abbr="nd";
			break;
		case 3:
			abbr="rd";
			break;
		default:;
		}
	}
	var timeElements=dateElements[4].split(":");
	var amPm=parseInt(timeElements[0])>12 ? "pm" : "am";
	return dateElements[0]+" "+dateElements[2]+abbr+" "+dateElements[1]+" "+timeElements[0]+":"+timeElements[1]+amPm;
}

gUtils.submitForm=function(aFormName)
{
	var form;
	if (navigator.userAgent.toLowerCase().match(/safari/))
	{
		var forms=document.getElementsByTagName('form');
		for (var i=0;i<forms.length;i++)
		{
			if (forms[i].getAttribute('name')==aFormName)
			{
				form=forms[i];
				break;
			}
		}
	}
	else
		form=document.forms[aFormName];
		
	form.submit();
};

/****************************************************************
	Disabling postcode control if EIRE selected
*/

gUtils.hidePostcodeIfRegionEIRE=function(aUpdatePostcodeValue)
{
	var postcodeControl,oldValue;
	var	regionControl=$('region_id');
	var regionIsEire=regionControl.options[regionControl.selectedIndex].innerHTML.toUpperCase()=='EIRE';
	
	$('postcode_control').style.display=(!regionIsEire ? "block" : "none");

	if (aUpdatePostcodeValue)
	{
		// find the postcode control
		postcodeControl=$('user_postcode');
		if (!postcodeControl)
			postcodeControl=$('postcode');
		if (postcodeControl)	// if found
		{
			if (regionIsEire)
			{
				// save the exising postcode in the element
				postcodeControl.setAttribute("value_x",postcodeControl.value);
				postcodeControl.value="na";
			}
			else
			{
				// get the element's saved postcode
				oldValue=postcodeControl.getAttribute("value_x");
				if (oldValue)
					postcodeControl.value=oldValue;
				if (postcodeControl.value=="na")
					postcodeControl.value="";
				postcodeControl.removeAttribute("value_x");
			}
		}
	}
};

/*****************************/


// this doesn't work for some reason (even though alert(Array.indexOf) tells us it's native code)
/*if (Array.indexOf!=null) 
{
	gUtils.arrayFind=function(aArray,aValue)
	{
debugMsg("array="+aArray+" "+"looking for : "+aValue+" found at:"+aArray.indexOf(aValue));
		return aArray.indexOf(aValue);
	}
}
else
{*/
	gUtils.arrayFind=function(aArray,aValue)
	{
		var index=gConst.kNotDefined;
		for (var i=0;i<aArray.length && index==gConst.kNotDefined;i++)
		{
			if (aArray[i]==aValue)
			{
				index=i;
			}
		}
		return index;
	};
//}

gUtils.poundFormat=function(aPence)
{
	var pounds=Math.floor(aPence/100);
	var pence=aPence%100;
	pence=(pence<10 ? "0"+pence : pence);
	return "\u00A3"+pounds+"."+pence;
}

gUtils.sendPrefToServer=function(aPref,aValue)
{
	var gPrefSetRequest=HTTP.newRequest();
	gPrefSetRequest.open('GET',"data/setPref.php?pref="+aPref+"&value="+aValue);
	gPrefSetRequest.send(null);		// and forget!
}

gUtils.setDivText=function(aDiv,aText)
{
	var oldText=aDiv.firstChild;
	var newText=document.createTextNode(aText);
	if (oldText)
		aDiv.replaceChild(newText,oldText);
	else
		aDiv.appendChild(newText);		
}

gUtils.clearDivText=function(aDiv)
{
	var text=aDiv.firstChild;
	if (text)
		aDiv.removeChild(text);
}

gUtils.getAbsoluteUrl=function(aRelativeUrl)
{
	var path=window.location.pathname.replace(/[^\/]*$/,'');	// remove filename
	return window.location.protocol+'//'+window.location.host+path+aRelativeUrl;
}

gUtils.gotoLocalPage=function(aRelativeUrl)
{
	window.location=gUtils.getAbsoluteUrl(aRelativeUrl);
}

gUtils.createDisplayNameAnchor=function(aText,aMaxDisplayLength)
{
	var anchor=document.createElement('a');
	gUtils.addDisplayTextToParent(anchor,aText,aMaxDisplayLength);		
	return anchor;	
}

gUtils.addDisplayTextToParent=function(aParent,aText,aMaxDisplayLength)
{
	if (aText.length>aMaxDisplayLength)
	{
		// reduce aMaxDisplayLength if there are several capitals or digits
		var matches=aText.match(/[A-Z0-9]/g);
		if (matches)
		{
			var proportion=matches.length/aText.length;
			if (proportion>0.1)
				aMaxDisplayLength=Math.ceil(aMaxDisplayLength*(1-proportion)*0.5)*2;	// ensure it's an even number
		}
		// split the text
		var halfLen=parseInt(aMaxDisplayLength/2);
		var regex=new RegExp("^(.{"+halfLen+"})(.*)(.{"+halfLen+"})$");
		var matches=aText.match(regex);
	
		// set the start of the title...
		aParent.appendChild(document.createTextNode(matches[1]));
		// the (hidden) middle...
		var hiddenMiddle=document.createElement('span');
		hiddenMiddle.style.display="none";
		hiddenMiddle.appendChild(document.createTextNode(matches[2]));
		aParent.appendChild(hiddenMiddle);
		// the ellipsis (inside a <span>)...
		var ellipsis=document.createElement('span');
		ellipsis.appendChild(document.createTextNode(".."));
		aParent.appendChild(ellipsis);
		// & the end of the title
		aParent.appendChild(document.createTextNode(matches[3]));
	}
	else
		aParent.appendChild(document.createTextNode(aText));
}

gUtils.getElementTlPos=function(aElement,aRelativeToId)
{
	var offset={x:0,y:0};
	var idMatch=false;
	while (aElement!==null && !idMatch)
	{
		offset.x+=aElement.offsetLeft;
		offset.y+=aElement.offsetTop;
		aElement=aElement.offsetParent;
		idMatch=(aRelativeToId!=undefined && aElement && aElement.id!=undefined && aRelativeToId==aElement.id);
	}
	return offset;
}

gUtils.getElementBrPos=function(aElement,aRelativeToId)
{
/*	var offset={x:aElement.offsetWidth,y:aElement.offsetHeight};
	var idMatch=false;
	while (aElement!==null && !idMatch)
	{
		offset.x+=aElement.offsetLeft;
		offset.y+=aElement.offsetTop;
		aElement=aElement.offsetParent;
		idMatch=(aRelativeToId!=undefined && aElement && aElement.id!=undefined && aRelativeToId==aElement.id);
	}*/
	var offset=gUtils.getElementTlPos(aElement,aRelativeToId);
	offset.x+=aElement.offsetWidth;
	offset.y+=aElement.offsetHeight;
	
	return offset;
}

gUtils.centreImageInSquare=function(aImageId,aSquareDimension,aW,aH)
{
	// no need to centre horiz (done by CSS) - just set the margin to centre vertically
	var marginTop=0;
	if (aW>aH)
		marginTop=Math.round((aSquareDimension-aH)/2);
	$(aImageId).style.marginTop=marginTop+"px";		
}

gUtils.addXmlListToArray=function(aArray,aXmlListId)
{
	var nodes,i,node,value,xmlList=$(aXmlListId);
	if (xmlList!==null)
	{
		nodes=xmlList.firstChild.childNodes;
		for (i=0;i<nodes.length;i++)
		{
			node=nodes.item(i);
//debugMsg(node.getAttribute('name')+" : "+node.getAttribute('value'));
			if (node.nodeType==1)
			{
				value=node.getAttribute('value');
				if (value.match(/^\d+$/))				// int (this goes wrong with leading zeroes!)
					value=parseInt(value);	
				else if (value.match(/^\d*\.\d*$/))		// float
					value=parseFloat(value);
				else if (value.match(/^\{.*\}$/))		// array
					value=value.match(/[^{^}^,]+/g);
				aArray[node.getAttribute('name')]=value;
			}
		}
	}
//debugMsg(JSON.stringify(aArray));
}

if (document.documentElement && document.documentElement.scrollWidth!==undefined)
	gUtils.getDocumentSize=function() { return {w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}; };
else if (document.body && document.body.scrollWidth)
	gUtils.getDocumentSize=function() { return {w:document.body.scrollWidth,h:document.body.scrollHeight}; };
else
	gUtils.getDocumentSize=function() { return {w:2000,h:2000}; };	

if (window.innerWidth)  			// all browsers except IE
{
	gUtils.getScrollPos=function() { return {x:window.pageXOffset,y:window.pageYOffset}; };
	gUtils.getViewportSize=function() { return {w:window.innerWidth,h:window.innerHeight}; };
}
else if (document.documentElement && document.documentElement.clientWidth) // for IE6 when there is a DOCTYPE
{
	gUtils.getScrollPos=function() { return {x:document.documentElement.scrollLeft,y:document.documentElement.scrollTop}; };
	gUtils.getViewportSize=function() { return {w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}; };
}
else if (document.body.clientWidth)	// for IE4, IE5, and IE6 without a DOCTYPE
{
	gUtils.getScrollPos=function() { return {x:document.body.scrollLeft,y:document.body.scrollTop}; };
	gUtils.getViewportSize=function() { return {w:document.body.clientWidth,h:document.body.clientHeight}; };
}
else								// default
{
	gUtils.getScrollPos=function() { return {x:0,y:0}; };
	gUtils.getViewportSize=function() { return {w:1024,h:768}; };
}

if (window.screenLeft)  // IE and others
    gUtils.setScrollPos=function(aX,aY){ window.screenLeft=aX;window.screenTop=aY; };
else if (window.screenX)  // Firefox and others
    gUtils.setScrollPos=function(aX,aY){ window.screenX=aX;window.screenY=aY; };

gUtils.scrollToBottom=function()
{
	var screenTopY=gUtils.getDocumentSize().h-gUtils.getViewportSize().h;
	if (screenTopY>0)
		window.scrollTo(0,screenTopY);
}

/*****************************/

gUtils.selectControlSetValue=function(aControlId,aValue)
{
	var ok=false;
	var formatControl=$(aControlId);
	var options=formatControl.options;
	for (var i=0;i<options.length;i++)
	{
		if (options[i].value==aValue)
		{
			formatControl.selectedIndex=i;
			ok=true;
			break;
		}
	}
	return ok;
}

/*****************************/

String.prototype.trim = function() 
{
	return this.replace(/^\s+|\s+$/g, ""); 
};

String.prototype.padLeft = function(aLen,aChar) 
{
	var ret="";
	for (var i=0;i<aLen-this.length;i++)
		ret+=aChar;
	return (ret+this);
};

String.prototype.htmlEntityDecode=function()
{
	var ret=this.replace(/&amp;/g,'&');
	ret=ret.replace(/&pound;/g,'£');
	ret=ret.replace(/&gt;/g,'>');
	ret=ret.replace(/&lt;/g,'<');
	ret=ret.replace(/&quot;/g,'"');
	return unescape(ret);
};

/*****************************************/

debugMsg=function(aText,aShowTime)
{
	if (aShowTime)
	{
		var now=new Date();
		aText=(now.getTime()%100000)+" : "+aText;
	}
	$('debug').innerHTML+=aText+"<br />";
}

debugMsgHtml=function(aHtmlText)
{
	$('debug').innerHTML+="<pre>"+aHtmlText.replace(/</g,'!').replace(/>/g,'|')+"</pre><br />";
}

//]]>