// Common Scripts
// version 1.0
// created by: Robert Gilks
// date: 31/8/00

var loadCommon = true;

//array to hold elements in which errors have been found during form error checking
var arrError = new Array;

// determine object model
var isDom = document.getElementById ? true:false;
var isNN4 = document.layers ? true:false;
var isIE = document.all ? true:false;

var browserVersion = parseFloat(navigator.appVersion);
var isOpera = (navigator.userAgent.indexOf("Opera") != -1);
var isMac = (navigator.appVersion.indexOf("Mac") != -1);
var isNetscape = (navigator.appName.indexOf("Netscape") != -1);

// Client-side Browser Check
var agt = navigator.userAgent.toLowerCase();
var is_ie = ((agt.indexOf("msie") != -1));
var is_ie3 = (is_ie && (browserVersion < 4));
var is_ie4 = (is_ie && (browserVersion == 4) && (agt.indexOf("msie 5")==-1) );
var is_ie4up = (is_ie && (browserVersion >= 4));
var is_ie5 = (is_ie && (browserVersion == 4) && (agt.indexOf("msie 5.0")!=-1) );
var is_ie5_5 = (is_ie && (browserVersion == 4) && (agt.indexOf("msie 5.5") !=-1));
var is_ie5up = (is_ie && !is_ie3 && !is_ie4);
var is_ie5_5up =(is_ie && !is_ie3 && !is_ie4 && !is_ie5);
var is_nav = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
var is_mac = (agt.indexOf("mac")!=-1);
var is_nav6up = (is_nav && (browserVersion >= 5));			
var is_nav4_5up = (is_nav && (browserVersion >= 4.5));
var is_ie4up  = (is_ie && (browserVersion >= 4));   

window.onresize = function() 
{ 
	nn4Resize();
};

// test if regular expressions are supported
var regExpSupported = false;
if (window.RegExp)
{
	var tempStr = "a";
	var tempReg = new RegExp(tempStr);
	if (tempReg.test(tempStr))
	{
	    regExpSupported = true;
	}
}

// Detect if Macromedia Shockwave Flash version 5 is present on the client.
var flashPlugin = false;
var flash5Installed = false;
var flash6Installed  = false;

if (navigator.plugins && navigator.plugins.length > 0)
{
	if (navigator.plugins["Shockwave Flash"])
	{
    	flashPlugin = true;	
	   	var words = navigator.plugins["Shockwave Flash"].description.split(" ");	
	   	for (i = 0; i < words.length; ++i) 
	   	{
			if (isNaN(parseInt(words[i])))
			{
			    continue;
			}
			if (words[i] == '5.0') flash5Installed = true;
			if (words[i] == '6.0') flash6Installed = true;
	   	}
		
	}
}
else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.userAgent.indexOf("Windows 95")>=0 || navigator.userAgent.indexOf("Windows 98")>=0 || navigator.userAgent.indexOf("Windows NT")>=0)) 
{
	document.write('<scr' + 'ipt language=VBScript\> \n');
	document.write('on error resume next \n');
	document.write('flash5Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.5")))\n');
	document.write('flash6Installed = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash.6")))\n');
	document.write('</scr' + 'ipt\> \n');
}

flashPlugin = flash5Installed || flash6Installed || flashPlugin;

// set the cookie in order to do server-side redirects dependant on flash plugin
document.cookie = "flashPlugin = " + flashPlugin + "; flash6Installed = " + flash6Installed;
//to delete cookie during testing
//var exp = new Date();  
//exp.setTime (exp.getTime() - 1);
//document.cookie = "flashPlugin = true; expires=" + exp.toGMTString();


// Deal with Netscape 4 page reload bug.
var winX = null;
var winY = null;
if (isNN4)
{
	winX = window.innerWidth;
	winY = window.innerHeight;
}

// Form headers and footers
var balloonHeader = '<table border="0" cellspacing="0" cellpadding="0" class="tblBackground"><tr><td><table border="0" cellspacing="1" cellpadding="4" align="center"><tr><td bgcolor="#FFFFFF">';
var balloonFooter = '</td></tr></table></td></tr></table>';

var formHeader = balloonHeader;
var formFooter = balloonFooter+'<br><br>';

function nn4Resize()
{
	if (isNN4 && (winX != window.innerWidth || winY != window.innerHeight))
	{
		history.go(0);
	}
}

// return an element on the page given the ID
// no support for netscape 4
function getElement(elementId)
{
	var el;					
	if (document.all)
	{
		el = document.all[elementId];
	} else {
		el = document.getElementById(elementId);
	}
	return el;
}

// Open a window of the desired size in the centre of the screen.
function openWindow(target_file, width, height, hasScrollBars)
{
	// ADD NAME FIELD and make sure it get's focus!!!
	var theWidth = width;
	var theHeight = height;
	var scrollBars = "scrollbars";
	if (hasScrollBars == false) scrollBars = "scrollbars=0";
	if ((theWidth == "")||(theWidth == null)) theWidth = 740;
	if ((theHeight == "")||(theHeight == null)) theHeight = 550;
	var theLeft = (screen.availWidth - theWidth)/2;
	var theTop = (screen.availHeight - theHeight)/2; 
	var popupWin = window.open(target_file, 'PC'+Math.floor(Math.random()*1000), 'top='+theTop+',left='+theLeft+',menubar=0,toolbar=0,location=0,directories=0,status=0,'+scrollBars+',resizable,width='+theWidth+',height='+theHeight);
}

// Test that a string could be a valid e-mail address 
function isEmail(str)
{
	if (regExpSupported)
	{
		var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
		var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{2,4})(\\]?)$");
		return (!r1.test(str) && r2.test(str));
	}
	else
	{
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
}

function dateAlert(theDate, theForm, field) 
{
    if (typeof (tableValidationAlert) !== "undefined") {
        if (tableValidationAlert)
            alertByTableCell(theDate[field][1]);
    }
    else
        alert(theDate[field][1]);
	if (isNN4) 
	{
		eval('document.layers["pageBody"].'+theForm+'.'+theDate[field][0]+'.focus()');
	}
	else
	{
	    eval(theForm+'.'+theDate[field][0]+'.focus()');
    }
}

// Allow ony certain types of information to be entered into text fields. 
// <input type="text" name="OfficeTel" onKeyUp="allowOnly('telephone',this)" onBlur="allowOnly('telephone',this)">
function allowOnly(type, field)
{
	if (regExpSupported)
	{
		switch(type)
		{
			case 'telephone':
				// to ensure only numbers, spaces and -'s can be put into a text field
				field.value = field.value.replace(/[^0-9 -]/g, '');
				field.value = field.value.replace(/  /g, '');
				field.value = field.value.replace(/--/g, '-');
				field.value = field.value.replace(/ -/g, ' ');
				field.value = field.value.replace(/- /g, '-');
				return;
				
			case 'integer':
			
				if(field.value.indexOf("-") == 0 && field.value.length > 1)
				{
					field.value = "-" + field.value.replace(/[^0-9]/g, '');
				}
				else
				{
					field.value = field.value.replace(/[^0-9]/g, '');
				}				

				if(field.value.indexOf("-") == 0 && field.value.length == 1)
				{
					field.value = field.value.replace(/[^0-9]/g, '');
				}				
				return;

			case 'percent':
			
				if(field.value.indexOf("-") == 0)
				{
					field.value = "-" + field.value.replace(/[^0-9]/g, '');
				}
				else
				{
					field.value = field.value.replace(/[^0-9]/g, '');
				}
				if(field.value<0)
				{
					field.value = 0;
				}
				
				if(field.value>100)
				{
					field.value = 100;
				}									
				return;
								
			case 'money': 
				//to ensure only numbers and .'s can be put into a text field, and to append 
				//two decimal places if none have been entered, and to trim any extra places
				field.value = field.value.replace(/[^0-9\.]/g, '');
				field.value = field.value.replace(/\.\./g, '.');
				if(field.value.indexOf(".")>=0)
				{				
					field.value = field.value.substr(0,(field.value.indexOf(".") + 3));
					switch(field.value.length - field.value.indexOf("."))
					{
						case 0:
							field.value = field.value + '0.00';
							break;
						case 1:
							field.value = field.value + '00';
							break;
						case 2:
							field.value = field.value + '0';
							break;
						}	
					}
				else
				{
					if (field.value.length == 0)
					{
						field.value = field.value + '0.00';
					}
					else
					{
						field.value = field.value + '.00';
					}	
				}												
				return;	
								
			case 'decimal': 
				if(field.value.indexOf("-") == 0)
				{
					field.value = "-" + field.value.replace(/[^0-9\.]/g, '');
				}
				else
				{
					field.value = field.value.replace(/[^0-9\.]/g, '');
				}
				field.value = field.value.replace(/\.\./g, '.');			
				return;
							
			case 'url':
				field.value = field.value.replace(/[ ]/g, '');
				if(field.value.indexOf("://") == -1 && field.value.length > 0)
				{
					field.value = "http://" + field.value;
				}
				return;		
			}		
		}		
	}

function checkValidEmail(theForm, fieldName, message)
{		
	if (isNN4)
	{
		if (eval('document.layers["pageBody"].'+theForm+'.'+fieldName+'.value') == "")
		{
			// no email address is valid
			return true;
		}
		if (!isEmail(eval('document.layers["pageBody"].'+theForm+'.'+fieldName+'.value')))
		{
		    if (typeof (tableValidationAlert) !== "undefined") {
		        if (tableValidationAlert)
		            alertByTableCell(message);
		    }
		    else
		        alert(message);
			eval('applyError(document.layers["pageBody"].'+theForm+'.'+fieldName+')');
			return false;
		}
	} 
	else
	{
	    if (eval(theForm+'.'+fieldName+'.value') == "")
	    {
		    // no email address is valid
		    return true;
	    }
	    if (!isEmail(eval(theForm+'.'+fieldName+'.value')))
	    {
	        if (typeof (tableValidationAlert) !== "undefined") {
	            if (tableValidationAlert)
	                alertByTableCell(message);
	        }
	        else
	            alert(message);
		    eval('applyError('+theForm+'.'+fieldName+')');
		    return false;
	    }
	}
	return true;
}
	
	//checks that at least one check box in a group has been selected, 
	//and if not gives the user the option to continue or not
	function checkCheckBoxSelected(theForm, fieldName, message, allowContinue){
		var isChecked = false;

		if (!(theForm.elements[fieldName]==null)){
			if (theForm.elements[fieldName].length > 0){
				for (var i = 0; i < theForm.elements[fieldName].length;i++){										
					if (theForm.elements[fieldName][i].checked){
						return true;
					}
				}	
			}
			else{							
				if (theForm.elements[fieldName].checked){
					return true;
					}
			}	
					
			//if we allow the user to continue even if they have not checked any boxes then 
			//give them a confirm box, otherwise give them an alert and return false
			if (allowContinue){
				if(confirm(message)){
					return true;
				}
				else{
					return false;
				}
			}
			else{
				alert(message);
				return false;
			}							
		}
		return	true;			
	}


function checkMatch(theForm, firstFieldName, secondFieldName, message) {
	if (isNN4) {
		if (eval('document.layers["pageBody"].'+theForm+'.'+firstFieldName+'.value != '+'document.layers["pageBody"].'+theForm+'.'+secondFieldName+'.value')) {
		    if (typeof (tableValidationAlert) !== "undefined") {
		        if (tableValidationAlert)
		            alertByTableCell(message);
		    }
		    else
		        alert(message); 
			eval('document.layers["pageBody"].'+theForm+'.'+secondFieldName+'.value = ""');
			eval('applyError(document.layers["pageBody"].'+theForm+'.'+secondFieldName+')');
			return false;
		}
	} else {
	if (eval(theForm+'.'+firstFieldName+'.value != '+theForm+'.'+secondFieldName+'.value')) {
	    if (typeof (tableValidationAlert) !== "undefined") {
	        if (tableValidationAlert)
	            alertByTableCell(message);
	    }
	    else
	        alert(message); 
		eval(theForm+'.'+secondFieldName+'.value = ""');
		eval('applyError('+theForm+'.'+secondFieldName+')');
		return false;
	}
	}
	return true;
}

// Test that the fields specified in theArr (nested array)
// are filled in theForm ( reference to a HTML form within a document )
// if not filled pop-up an alert and focus on the unfilled field.
// var theArr = new Array( new Array('FIELD NAME','message'), new Array('FIELD NAME','message')...);
function checkFieldsFilled(theForm, theArr) {
	for (var i in theArr) {	
		if (typeof(theArr[i]) == 'object') {
			if (isNN4) {
			    if (eval('document.layers["pageBody"].' + theForm + '.' + theArr[i][0] + '.value.replace(/\s/g, "") == ""')) {
			        if (typeof (tableValidationAlert) !== "undefined") {
			            if (tableValidationAlert)
			                alertByTableCell(theArr[i][1]);
			        }
			        else
			            alert(theArr[i][1]); 
					if (theArr[i][2] != "noFocus"){
						 eval('applyError(document.layers["pageBody"].'+theForm+'.'+theArr[i][0]+')');
					}
					return false;
				}
			} 
			else 
			{
				var elem = eval(theForm+'.'+theArr[i][0]);
				var strVal = elem.value;
				//replace all spaces 
				if(strVal.indexOf(" ") > -1)
				{
					strVal = strVal.replace(/\s/g, "");
				}
				
				if (strVal == "")
				{
				    if (typeof (tableValidationAlert) !== "undefined") {
				        if (tableValidationAlert)
				            alertByTableCell(theArr[i][1]);
				    }
				    else
				        alert(theArr[i][1]); 
					if (theArr[i][2] != "noFocus") {
						eval('applyError(' + theForm+'.'+theArr[i][0]+')');
					}
					return false;
				}
			}
			//checkFieldsFilled(theArr[i]);
		}									
	}
	return true;
}

// Test that the fields specified in theArr (nested array)
// are filled in theForm ( reference to a HTML form within a document )
// if not filled focus on the unfilled field and returns index  of unfilled field.
// var theArr = new Array( new Array('FIELD NAME','message'), new Array('FIELD NAME','message')...);
function checkFieldsFilledToTable(theForm, theArr) {
    for (var i in theArr) {
        if (typeof (theArr[i]) == 'object') {
            if (isNN4) {
                if (eval('document.layers["pageBody"].' + theForm + '.' + theArr[i][0] + '.value.replace(/\s/g, "") == ""')) {
                    alertByTableCell(theArr[i][1]);
                    if (theArr[i][2] != "noFocus") {
                        eval('applyError(document.layers["pageBody"].' + theForm + '.' + theArr[i][0] + ')');
                    }
                    return false;
                }
            }
            else {
                var elem = eval(theForm + '.' + theArr[i][0]);
                var strVal = elem.value;
                //replace all spaces 
                if (strVal.indexOf(" ") > -1) {
                    strVal = strVal.replace(/\s/g, "");
                }

                if (strVal == "") {
                    alertByTableCell(theArr[i][1]);
                    if (theArr[i][2] != "noFocus") {
                        eval('applyError(' + theForm + '.' + theArr[i][0] + ')');
                    }
                    return false;
                }
            }            
        }
    }
    return true;
}

// Checks if date passed is valid
// will accept dates in following format:
// isDate(dd,mm,ccyy)
function checkDate (theForm, theDate) {

	var today = new Date();	
	
	if (isNN4) {
		year = eval('document.layers["pageBody"].'+theForm+'.'+theDate[2][0]+'.value');
		objYear = eval('document.layers["pageBody"].'+theForm+'.'+theDate[2][0]);
		month = eval('document.layers["pageBody"].'+theForm+'.'+theDate[1][0]+'.value');
		objMonth = eval('document.layers["pageBody"].'+theForm+'.'+theDate[1][0]);
		day = eval('document.layers["pageBody"].'+theForm+'.'+theDate[0][0]+'.value');
		objDay = eval('document.layers["pageBody"].'+theForm+'.'+theDate[0][0]);
	} else {
		year = eval(theForm+'.'+theDate[2][0]+'.value');
		objYear = eval(theForm+'.'+theDate[2][0]);
		month = eval(theForm+'.'+theDate[1][0]+'.value');
		objMonth = eval(theForm+'.'+theDate[1][0]);
		day = eval(theForm+'.'+theDate[0][0]+'.value');
		objDay = eval(theForm+'.'+theDate[0][0]);
	}	
	
	if (day == '' && month == '' && year == '')
	{
	    return true;
	}
	
	month = month - 1;
	// First check than they fields are within reasonable ranges
	if ((day < 1) || (day >  31)) { dateAlert(theDate, theForm, '0'); applyError(objDay); return false; }		
	if ((month < 0) || (month > 11)) { dateAlert(theDate, theForm, '1'); applyError(objMonth); return false; }	
	if ((year < 1850)) { dateAlert(theDate, theForm, '2'); applyError(objYear); return false; }
    
	var test = new Date(year,month,day);
	
	// Now check that the date actually exists
	if (day != test.getDate()) { dateAlert(theDate, theForm, '0'); applyError(objDay); return false; }	
	if (month != test.getMonth()) {	dateAlert(theDate, theForm, '1'); applyError(objMonth); return false; }	    
	if (year != y2k(test.getYear())) { dateAlert(theDate, theForm, '2'); applyError(objYear); return false; }
	return true;
}

function y2k(number) {
	return (number < 1000) ? number + 1900 : number;
}

// Checks if time passed is valid
// will accept time in following format:
// isTime(hh,mm)
function checkTime (theForm, theTime) {

	if (isNN4) {
		minute = eval('document.layers["pageBody"].'+theForm+'.'+theTime[1][0]+'.value');
		objMinute = eval('document.layers["pageBody"].'+theForm+'.'+theTime[1][0]);
		hour = eval('document.layers["pageBody"].'+theForm+'.'+theTime[0][0]+'.value');
		objHour = eval('document.layers["pageBody"].'+theForm+'.'+thetheTimeDate[0][0]);
	} else {
		minute = eval(theForm+'.'+theTime[1][0]+'.value');
		objMinute = eval(theForm+'.'+theTime[1][0]);
		hour = eval(theForm+'.'+theTime[0][0]+'.value');
		objHour = eval(theForm+'.'+theTime[0][0]);
	}	
	
	// Check that the fields are within reasonable ranges
	if ((hour < 0) || (hour >  23)) { timeAlert(theTime, theForm, '0'); applyError(objHour); return false; }	
	if ((minute < 0) || (minute > 59)) { timeAlert(theTime, theForm, '1'); applyError(objMinute); return false; }
	
	// Now check that the time actually exists 
	if (!hour) { timeAlert(theTime, theForm, '0'); applyError(objHour); return false; }	
	if (!minute) { timeAlert(theTime, theForm, '1'); applyError(objMinute); return false; }	  
	
	return true;
}

function timeAlert(theTime, theForm, field) {
	alert(theTime[field][1]);
	if (isNN4) {
		eval('document.layers["pageBody"].'+theForm+'.'+theTime[field][0]+'.focus()');
	} else {
		eval(theForm+'.'+theTime[field][0]+'.focus()');
	}
}

//This function replaces double quotes with single quotes.
//To be used for field that reqire confirmboxes to put up on other pages
// eg when deleteing a document/advert/user. If not used may cause javascript error!
function rplQuote(theForm, theField){
	var objField;
	if (isNN4) {
		objField = eval('document.layers["pageBody"].'+theForm + "." + theField);
	} else {
		objField = eval(theForm + "." + theField);
	}
	var tempString = objField.value;
	while (tempString.indexOf('"')!= -1){
		tempString = tempString.replace('"',"'");
	}
	objField.value = tempString;
}

//function used when remove button for uploaded images if clicked
//	1) creates comma seperated list of image files to be deleted.
//	2) sets hidden field to zero length string
//	3) Sets Img.src to spacer.gif

var commaSpacer = "";
function removeImage(objFileName,objDeleteList,objImage, strPath){
	objDeleteList.value = objDeleteList.value + commaSpacer + objFileName.value;
	objFileName.value = "";
	objImage.src = strPath + "/images/common/spacer.gif";
	commaSpacer = ",";
}

//function used when remove button for uploaded attachments if clicked
//	1) creates comma seperated list of attachment files to be deleted.
//	2) sets hidden field to zero length string

var commaSpacer = "";
function removeAttachment(objFileName,objDeleteList, strPath){
	objDeleteList.value = objDeleteList.value + commaSpacer + objFileName.value;
	objFileName.value = "";
	commaSpacer = ",";
}

var bolCheckedAll = false;

function checkAll(theForm,strCBoxName,theButton){
	if (bolCheckedAll){
		for (i = 0;i<theForm.elements[strCBoxName].length;i++){
			theForm.elements[strCBoxName][i].checked = false;
		}
		theButton.value ="Check All";
		bolCheckedAll = false;
	}
	else {
		for (i = 0;i<theForm.elements[strCBoxName].length;i++){
			theForm.elements[strCBoxName][i].checked = true;
		}
		theButton.value ="Clear All";
		bolCheckedAll = true;
	}
}

function checkAllByValue(theForm,strElemValue,theButton){
	if (bolCheckedAll){
		for (i=0;i<theForm.elements.length;i++){
			if (theForm.elements[i].value == strElemValue){
				theForm.elements[i].checked = false;
				}
			}			
		theButton.value ="Check All";
		bolCheckedAll = false;
	}
	else {
		for (i=0;i<theForm.elements.length;i++){
			if (theForm.elements[i].value == strElemValue){
				theForm.elements[i].checked = true;
				}
			}			
		theButton.value ="Clear All";
		bolCheckedAll = true;
	}
}

//function moves cursor to next date box when / is pressed
function moveDateCursor(newElement){
	if (document.all) {
		e = window.event;
	}
	if (document.layers){
		if (e.which == 47)
		{
			return false;
		}
	}
    else if (document.all){
		if (e.keyCode == 47)
		{
			e.returnValue = false;
		}
	}
}

//function moves cursor to next time box when : or . is pressed
function moveTimeCursor(newElement){
	if (document.all) {
		e = window.event;
	}
	if (document.layers){
		if (e.which == 58 || e.which == 46)
		{
			return false;
		}
	}
    else if (document.all){
		if (e.keyCode == 46)
		{
			e.returnValue = false;
		}//For some wierd reason can't use or '| nor ||' statments
		else if(e.keyCode == 58)
		{
			e.returnValue = false;
		}
	}
}

var intClickCnt = 1;
function doClickNonediable(theButton){
	intClickCnt++;
	if (intClickCnt >= 3)
	{
		alert("Please click the '" + theButton.value + "' button to edit this field.");
		intClickCnt=0;
		theButton.focus();
	}
}


function printFormat(theDiv, pageTitle) {	
	var theWidth = 600;
	var theHeight = screen.availHeight-200;
	var theLeft = (screen.availWidth - theWidth)/2;
	var theTop = (screen.availHeight - theHeight)/2; 
	var win = window.open("/print.htm", "", 'top='+theTop+',left='+theLeft+',menubar=1,toolbar=1,location=0,directories=0,status=0,scrollbars,resizable,width='+theWidth+',height='+theHeight);
	win.document.write("<html>");
	win.document.write("<head>");
	win.document.write('<link rel="STYLESHEET" type="text/css" href="/interfaces/html/common/main.css"/>');
	win.document.write('<link rel="STYLESHEET" type="text/css" href="/interfaces/html/common/print.css"/>');
	win.document.write('<script>var flashPlugin = false;</script>');
	win.document.write('<script>var formHeader = ""; var formFooter = ""</script>');
	win.document.write("</head>");				
	win.document.write("<body>");
	if (pageTitle){
		win.document.write("<h1>");
		win.document.write(pageTitle.replace("<","&lt;").replace(">","&gt;"));
		win.document.write("</h1>");
		win.document.write("<br/>");
		}
	if (isDom) {
		win.document.write(document.getElementById(theDiv).innerHTML);
	} else if (isIE) {
		win.document.write(document.all[theDiv].innerHTML);
	} else if (isNN4) {
		win.document.write(document.layers['pageBody'].toString());
	}
	win.document.write("</body>");
	win.document.write("</html>");
	win.document.close();
}

function fade(theLayer, vis) {
	if (vis == null){		
		if (theLayer.style.visibility == "hidden"){
			vis = "visible";
		} else {
			vis = "hidden";
		}
	}
	if (isIE) {
		if (theLayer.filters.length > 0) {
			if (typeof(theLayer.filters[0]) == "object") {
				theLayer.filters.blendTrans.Apply();
				theLayer.style.visibility = vis;
				theLayer.filters.blendTrans.Play();
			} else { theLayer.style.visibility = vis; }
		} else { theLayer.style.visibility = vis; }
	} else { theLayer.style.visibility = vis; }
}

function getWindowWidth() {		
	if (isIE) {
		return document.body.clientWidth;
	}
	if (isDom) {
		return document.width;
	}
	if (isNN4) {
		return document.width;
	}
	return false;
}

			
// show ticker items one after another
// the ticker layers are created using the ticker.xsl stylesheet
function showItem(tickerName, i, count, displayTime, transitionTime) 
{
	var lay1, lay2, intNext, intPrev;
	if (i==1){
		intPrev = count;
	}
	else {
		intPrev = i-1;
	}
	
	if (isIE)
	{
		lay1 = document.all[tickerName+'Item'+ intPrev];
		if (lay1)
		{
		    lay1.style.filter = "blendTrans(duration="+transitionTime+")";
		}
		lay2 = document.all[tickerName+'Item'+i];
		if (lay2)
		{
		    lay2.style.filter = "blendTrans(duration="+transitionTime+")";
		}
	}
	else if (isDom) 
	{
		lay1 = document.getElementById(tickerName+'Item'+ intPrev);
		if (lay1)
		{
		    lay1.style.width = localAdWidth;
		}
		lay2 = document.getElementById(tickerName+'Item'+i);
		if (lay2) 
		{
		    lay2.style.width = localAdWidth;
		}
	}
	else if (isNN4) 
	{						
		lay1 = document.layers[tickerName+'Item'+ intPrev];
		lay2 = document.layers[tickerName+'Item'+i];
	}

	if (count > 1) 
	{
		if (i == count)
		{
			next = 1;
		}
		else 
		{
			next = i + 1;
		}
		//alert(next)
		if (lay1) {fade(lay1,"hidden");}
		if (lay2) {fade(lay2,"visible");}
		setTimeout("showItem('"+tickerName+"',"+ next +","+count+","+displayTime+","+transitionTime+")", displayTime);
	}
	else {
		fade(lay2,"visible");
	}
}


// Switches the hints on and off by adding a setting to the query string
function switchHints(setting) {	
	if (String(location).indexOf("?") != -1) { // check if query string exists
		if (String(location).indexOf("showHints=false") != -1)
		{
			if (setting == 'false')
			{
			    return;
			}
			location = String(location).replace(/showHints=false/i,"showHints=true");
			return;
		}
		if (String(location).indexOf("showHints=true") != -1)
		{
			if (setting == 'true')
			{
			    return;
			}
			location = String(location).replace(/showHints=true/i,"showHints=false");
			return;
		}		
		location += '&showHints=' + setting;
		return; 	
	}
	else
	{
		location += '?showHints=' + setting;
	}
}

// change the values that a chart displays
// works in conjunction with charts.xsl include
function setChart(movieId, chartType, label, colour, args)
{
	if (flashPlugin == true)
	{		
		var str = "";
		str = '<object id="'+movieId+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" width="500" height="180">';
		str += '<param name="movie" value="/interfaces/html/flash/'+chartType+'.swf?title='+label+'&amp;colour='+colour+'&amp;args='+args+'"/>';
		str += '<param name="quality" value="high"/>';
		str += '<param name="bgcolor" value="#FFFFFF"/>';
		str += '<embed src="/interfaces/html/flash/'+chartType+'.swf?title='+label+'&amp;colour='+colour+'&amp;args='+args+'" quality="high" bgcolor="#FFFFFF" swliveconnect="true" name="+movieId+" width="500" height="180" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"/>';
		str += '</object>';
		
		if (isIE && !isMac)
		{
			var ref = document.all[movieId];
			ref.SetVariable("args", args);
			ref.SetVariable("colour", colour);
			ref.SetVariable("title", label);
			ref.Rewind();
			ref.Play();
			return;
		}
		if (isIE && isMac)
		{
			var ref = document.all[movieId+"Div"];
			ref.innerHTML = str;
			return;
		}
		if (isDom)
		{
			var ref = document.getElementById(movieId+"Div");
			ref.innerHTML = str;
			return;	
		}
	}
	else
	{
		openWindow("/flash/getFlash.asp?feature=Interactive%20Charts", "400", "200");
	}
}

// The following function is used on the menu to show hidden items.
// It requires 2 arrays to have been created
// menuIds[0] is an array of all the top level menu items.
//olly infact menuIds[0] is a 1 based array of all sub menu item
// menuIds[1] is an array of all the second level menu items.
function showHideChildren() 
{
    // first argument to function is the parent id, then the children ids	
	var linkRef, ref;

	// hide all the second level menu items
	for ( i = 1 ; i < menuIds[0].length ; i++ ) 
	{			
		getElement(menuIds[0][i]).style.display = 'none';
	}
	
	// switch all the indicators that show '-' to '+' except for the item just clicked	
	for ( i = 2 ; i < menuIds[1].length ; i+=2 ) 
	{		
		if (menuIds[1][i+1] == '1' && menuIds[1][i] != arguments[0]) 
		{
			ref = getElement(menuIds[1][i]+"Indicator");									
			if (ref.innerHTML.indexOf("-") >= 0) 
			{
				ref.innerHTML = '+';				
			}
		}
	}
	
	// switch the indicator of the item just clicked, if it changes to a '-' draw the menu items
	// beneath it.
	ref = getElement(arguments[0]+"Indicator");
	if (ref.innerHTML == "-") {
		ref.innerHTML = '+';
	} else {
		ref.innerHTML = '-';
		for ( i = 1 ; i < arguments.length ; i++ ) {
			ref = getElement(arguments[i]).style.display = 'block';
			linkRef = getElement(arguments[i]+"Link");

			//**************** Commented this out, as it doesn't seem to have an affect on the menu item as the colour is set in the xsl************
			//if ( arguments[i] == "menuItem"+pageId ) {
			//	linkRef.style.color = pageColour;
			//	} 
			//else{

			//	if (siteTypeId == 616 && isAdmin!=1) {
			//		linkRef.style.color = pageColour;
			//		}
			//	else{
			//		linkRef.style.color = 'black';
			//		}	
					
			//}
		}
	}
}

//Function to be overwritten on individual pages
function after_Onload(){}

//Called from popup onload events
function focus_Onload(){
	focus();
	after_Onload();
}

//Function to be overwritten on individual pages
function before_Unload(){}

function moveLayerWithFocus(objElem, objLayer, adjustTop, aduststLeft){
	//Get distance from top of body
	var tmpObj = objElem;
	var intTopPx = 0;
	var intLeftPx = 0;
	while(typeof(tmpObj)== "object")
	{
		intTopPx += tmpObj.offsetTop;
		intLeftPx += tmpObj.offsetLeft;
		tmpObj = tmpObj.offsetParent;
		if (tmpObj.tagName.toLowerCase() == "body"){break;}
	}
	intLeftPx += aduststLeft;
	objLayer.style.top = (intTopPx + adjustTop);
	objLayer.style.left = (intLeftPx);
	//If bottom goes of the end of the page make sure the top of the layer is at the top of the page
	if(intTopPx + objLayer.clientHeight > document.body.clientHeight + document.body.scrollTop)
	{
		document.body.scrollTop = intTopPx + adjustTop - 30;
	}
	objLayer.style.visibility = "visible";
}

function validateOvers(elem)
{	
	var j = 0;
	var c;
	for (var i = 0; i < elem.value.toString().length; i++)
	{
		c = elem.value.toString().substr(i, 1);
		if (c == '.')
		{
			j++;
	    }
		if (j >= 2) 
		{
			alert("overs should be in the format overs.balls, eg 5.1, 5.2 etc");
			applyError(elem);
			return false;
		}
	}
	
	if ((elem.value * 10) % 1 > 0)
	{
		alert("overs should be in the format overs.balls, eg 5.1, 5.2 etc");
		applyError(elem);
		return false;
	}
	else if (elem.value % 1 > 0.5)
	{
		alert("only six balls per over please!");
		applyError(elem);
		return false;
	}
	else
	{
		return true;
	}
}

function convertOversToDecimal(val){
	var tmpVal, floorVal;
	//get the fraction part of the overs	
	floorVal = Math.floor(val);
	tmpVal = val - floorVal;
	//convert the fraction part of the overs to a base 10 number
	tmpVal = (tmpVal * 10 / 6);
	//add it back to the floor of the value
	tmpVal = tmpVal + floorVal;
	
	return tmpVal;
}

function convertDecimalToOvers(val)
{	
	var tmpVal, floorVal;
	//get the fraction part of the value	
	floorVal = Math.floor(val);
	tmpVal = val - floorVal;	
	//convert the fraction part of the overs to a base 6 number
	tmpVal = (tmpVal * 6 / 10);
	//add it back to the floor of the value
	tmpVal = tmpVal + floorVal;
	return tmpVal;
}

function RndToNumDecPlaces(val, decPlaces)
{		
	//done like this because Math.pow function returns inconsistent values
	for (var i = 1;  i <= decPlaces; i++)
	{
		val = val * 10;
	}			
	val = Math.round(val);
	for (var j = 1; j <= decPlaces; j++)
	{
		val = val / 10;
	}
	return val;
}

function validateWkts(elem)
{
	if (elem.value > 10 || elem.value < 0)
	{
		alert("Number of wickets must be between 0 and 10");
		applyError(elem);
		return false;
	}
	else
	{
		return true;
	}
}

function applyError(elem)
{
	arrError[arrError.length] = new Array(elem, elem.className);
	elem.className = "focused";
	elem.focus();
}

function clearExistingErrors()
{
	var i;
	for(i=0; i < arrError.length; i++)
	{
		arrError[i][0].className = arrError[i][1];
	}
	arrError = new Array;
}

var hexVals = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F");
var unsafeString = "\"<>%\\^[]`";

function URLEncode(val)
{
	var state   = 'urlenc';
	var len     = val.length;
	var backlen = len;
	var i       = 0;

	var newStr  = "";
	var frag    = "";
	var encval  = "";

	for (i=0;i<len;i++)
	{
		if (isURLok(val.substring(i,i+1))) 
		{
			newStr = newStr + val.substring(i,i+1);
		}
		else 
		{
			tval1=val.substring(i,i+1);
			newStr = newStr + "%" + decToHex(tval1.charCodeAt(0),16);
		}
	}
	return newStr
}

function decToHex(num, radix) // part of URL Encode
{
	var hexString = "";
	while (num >= radix)
	{
		temp = num % radix;
		num = Math.floor(num / radix);
		hexString += hexVals[temp];
	}
	hexString += hexVals[num];
	return reversal(hexString);
}

function reversal(s) // part of URL Encode
{
        var len = s.length;
        var trans = "";
        for (i=0; i<len; i++)
        {
                trans = trans + s.substring(len-i-1, len-i);
        }
        s = trans;
        return s;
}

function isURLok(compareChar) // part of URL Encode
{
        if (unsafeString.indexOf(compareChar) == -1 && compareChar.charCodeAt(0) > 32 && compareChar.charCodeAt(0) < 123) 
        {
                return true;
        }
        else
        {
                return false;
        }
}

function toggleElement(element, bol){
	var className
	if (bol){className = ""}
	else{className = "noEdit"}
	
	if (element.length > 1){
		if(element[0].type == "radio" || element[0].type == "checkbox"){
			for (i=0; i<element.length; i++){
				element[i].disabled = !bol;
			}
		}
		else if(element.type == 'select-one'|| element.type == 'select-multiple'){
			element.readOnly = !bol;
			element.disabled = !bol;
			element.className = className;
		}
		else{
			element.readOnly = !bol;
			element.className = className;
		}
	}
	else
	{
		if(element.type == "radio" || element.type == "checkbox"){
			element.disabled = !bol;
		}
		else if(element.type == 'select-one'|| element.type == 'select-multiple'){
			element.readOnly = !bol;
			element.disabled = !bol;
			element.className = className;
		}
		else{
			element.readOnly = !bol;
			element.className = className;
		}
	}
}

function clearElement(element){
	if (element.length > 1){
		if(element[0].type == "radio" || element[0].type == "checkbox"){
			for (i=0; i<element.length; i++){
				element[i].checked = false;
			}
		}
		else if(element.type == 'select-one'|| element.type == 'select-multiple'){
			element.value = "";
		}
		else{
			element.value = "";
		}
	}
	else{
		if(element.type == "radio" || element.type == "checkbox"){
			element.checked = false;
		}
		else if(element.type == 'select-one'|| element.type == 'select-multiple'){
			element.value = "";
		}
		else{
			element.value = "";
		}
	}
}

function limitTextAreaLength(elem, max){				
	if(elem.value.length > max){		
		elem.value = elem.value.substring(0,max);
		}			
}

//pass in a reference to the form, and the elad characters of the caption field
//which is logically connected to the image by the image number, appended to the 
//end of the caption field text.
//Also pass in an array of the images that can exist on the page.
function checkImageCaptions(theFormRef, captionFieldText, arrImages){						
						
	var captionField = ''
							
	for (var i = 0; i < arrImages.length; i++){		
		if (theFormRef.elements[arrImages[i]].value != '')
		{	
			captionField = captionFieldText + (i + 1);					
			if (theFormRef.elements[captionField].value == '')
			{
				alert("Due to regulations, each image requires a caption, even if you have elected not to display it!");
				applyError(theFormRef.elements[captionField]);
				return false;
			}
		}
	}
}

//-----------------------------------------------------------------------------
//Scoreboard stuff

var ecbTimer = setTimeout("ecbMatches()", 600);

function ecbMatches(timeinterval)
{
	if (document.getElementById("EcbPage") == null)
	{
		return null;
	}

	if(timeinterval)
	{
		timeinterval = timeinterval * 1000;
	}
	else
	{
		timeinterval = 8000;
	}

	if(ecbTimer != "")clearTimeout(ecbTimer);

	

	var page = parseInt(document.getElementById("EcbPage").innerHTML) + 1;

	var totalpages = parseInt(document.getElementById("EcbTotalPages").innerHTML);

	if(page > totalpages)
	{

		page = 1;

	}



	document.getElementById("EcbPage").innerHTML = page;

	for(var i=1; i<=totalpages; i++){

		if(i==page){

			document.getElementById("EcbMatchesPage" + i).style.display = "block";

		}else{

			document.getElementById("EcbMatchesPage" + i).style.display = "none";

		}

	}



	

	ecbTimer = setTimeout("ecbMatches()",timeinterval);

}

//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//Ask search functionality

function switchSearchForm(frm) {

	if(frm == "pc"){

		document.getElementById("rbSiteSearch1").checked = "checked";

		document.getElementById("keyword-search").value = document.getElementById("askText").value;

		document.getElementById("PcSearch").style.display = "block";

		document.getElementById("AskSearch").style.display = "none";

		

	} else {

		document.getElementById("rbAsk2").checked = "checked";

		document.getElementById("askText").value = document.getElementById("keyword-search").value;

		document.getElementById("PcSearch").style.display = "none";

		document.getElementById("AskSearch").style.display = "block";

	}

}


function IsValidSiteSearch()
{
	if (document.getElementById('keyword-search').value =='enter keyword')
	{
		return false;
	}

	return true;
}
// scripts added by Adi

function getWhatever(strUrl) {
    var strReturn = "";
    jQuery.ajax({
        url: strUrl, success: function(html) { strReturn = html; }, async: false
    });
    return strReturn;
}

//-----------------------------------------------------------------------------

//Calculates left and top offset for the page element 
function getElementPosition(ctrl) {

    var offsetLeft = 0;
    var offsetTop = 0;
    while (ctrl) {
        offsetLeft += ctrl.offsetLeft;
        offsetTop += ctrl.offsetTop;
        ctrl = ctrl.offsetParent;
    }

    return { left: offsetLeft, top: offsetTop };
}
function postWhatever(strUrl, data) {
    var strReturn = "";
    jQuery.ajax({ type: "POST", data: data,
        url: strUrl, success: function (html) { strReturn = html; }, async: false
    });
    return strReturn;
}
 function alertByTableCell(message) {
    if (document.getElementById("validationError") == null) {
        var theTable = document.getElementById("userDetailsTable");
        var theRow = theTable.insertRow(0);
        var theCell = theRow.insertCell(0);
        theCell.setAttribute('id', 'validationError');
        theCell.setAttribute('colSpan', '3');
    }
    else {
        var myCell = document.getElementById("validationError");
        var children = myCell.childNodes;
        for(var count = children.length-1; count >= 0; count--)
            if( children[count].nodeType == 3) //TEXT_NODE
                myCell.removeChild(children[count]);
    }
    var theCell = document.getElementById("validationError");
    var theText = document.createTextNode(message);
    theCell.appendChild(theText);
    var pos = getElementPosition(theCell);
    var t = pos.top;
    window.scrollTo(0, t);
}


//-----------------------------------------------------------------------------

