function getElement(objectid) {
	if (typeof objectid == 'object') {
		return objectid;
	} else if (typeof objectid == 'string') {
		return crossbrowser_return_documentobject(objectid);
	}
}

function addHandler(element,eventname,handler,capture) {
	// cross browser attach event handler
	// could provide fallback when enither addEventListener or attachEvent is available
	// could all addEventLister to take parameter for capture bubble up of event (currently just set to false)
	if (capture == undefined) { capture = false; }
	if (element.addEventListener) {
		element.addEventListener(eventname,handler,capture);
		return;
	}
	if (element.attachEvent) {
		element.attachEvent('on'+eventname,handler);
		return;
	}
}

function applyPrompt(obj,prompt) {
	// Fills text input with prompt that is cleared while it is in use

	function setPrompt() {
		if (obj.value == '') obj.value = prompt;
	}

	function clearPrompt() {
		if (obj.value == prompt) obj.value = '';
	}

	// set prompt on field 
	obj.value = prompt;
	// clear prompt while in use
	addHandler(obj,'focus',clearPrompt);
	// show prompt after field was used
	addHandler(obj,'blur',setPrompt);
	// clear prompt when form is submitted
	addHandler(obj.form,'submit',clearPrompt,false);
}

function crossbrowser_return_documentobject (objectid) {
	
	if (document.getElementById) {
		return(document.getElementById(objectid));
	} else if (document.all) {
		return(document.all[objectid]);
	} else {
		return(null);
	}
	
}

/* ######################################################################### */

function toggleVisibility(id, idsToHide) {
	
	if(idsToHide){
		var myObject = eval(idsToHide);
		//var str = "HIDEING!!!!!\n\n";
		
		for(prop in myObject) {
			if(myObject[prop]!= id) {
				//str += myObject[prop] + "\n";
				var objct = crossbrowser_return_documentobject(myObject[prop]);
				objct.style.display = 'none';
			}
		}
		
		//alert(str);
	}
	
	
	var obj = crossbrowser_return_documentobject(id);
	
	if (obj) {
		if (obj.style.display != 'none') {
			obj.style.display = 'none';
		} else {
			obj.style.display = '';
		}
	}

}

/* ######################################################################### */

function gotoURL(URL,item) {
	if (confirm('This '+item+' will be removed!\nAre you sure?')) {
		window.location=URL;
	}
}

/* ######################################################################### */

function addSearchEngine(name,ext,cat,type) {
	if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
		window.sidebar.addSearchEngine(
		"http://www.scran.ac.uk/search/" + name + ".src",
		"http://www.scran.ac.uk/search/" + name + "."+ ext, name, cat );
	} else {
		alert("You will need a Mozilla based browser to install a search plugin.");
	}
}

/* ######################################################################### */

/*
	are any of the following still used?
*/

function addToSearch(b,t){	//Add a new term onto the current search term
	oldSearch = document.searchscran.search_term.value;
	newSearch = oldSearch + " " + b + " " + t;
	document.searchscran.search_term.value = newSearch;
}
/*
var openedWindows = {}; // only remembered from current page - is there another way to check if window is open
function openNewWindow(URLtoOpen, windowName, windowFeatures) {
	if (!openedWindows[windowName] || openedWindows[windowName].closed) {
		openedWindows[windowName]=window.open(URLtoOpen, windowName, windowFeatures);
	}
	if (openedWindows[windowName]) {
		openedWindows[windowName].focus();
	} else {
		alert('Did not have focus method');
	}
	return (openedWindows[windowName]) ? false : true;
}
function openWindowAtFront(URLtoOpen,windowName,windowFeatures) {
	if (!openedWindows[windowName] || openedWindows[windowName].closed) {
		//alert('opened window');
		openedWindows[windowName]=window.open(URLtoOpen, windowName, windowFeatures);
	}
	if (openedWindows[windowName]) {
		openedWindows[windowName].focus();
	} else {
		alert('Did not have focus method 2');
	}
	//alert('focused window');
	//alert ('returning '+String((openedWindows[windowName]) ? false : true));
	return (openedWindows[windowName]) ? false : true;
}
*/

function openNewWindow(URLtoOpen, windowName, windowFeatures) {
	newWindow=window.open(URLtoOpen, windowName, windowFeatures);
}
function openWindowAtFront(URLtoOpen,windowName,windowFeatures) {
	// well that seems to run in safari
	openedWindow = window.open(URLtoOpen,windowName,windowFeatures);
	if (openedWindow) {
		focused = openedWindow.focus(); // JW: Cannot find out why this doesn't work on Safari (Answer: Its just Safari for Windows that has problems)
		return false;
	}
	return true;
}


//Macromedia function. why reinvent the wheel.

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
	if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
		document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
	else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

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;
}

//used to create a search query from the 3 values entered in the full search page.
function doQSearch(){
	var searchTerm ="";
	searchTerm = document.ignoreForm.query1.value;
	if (document.ignoreForm.query2.value != "") {
		searchTerm = searchTerm+" "+document.ignoreForm.bool1.value+" "+document.ignoreForm.query2.value;
	}
	if (document.ignoreForm.query3.value != "") {
		searchTerm = searchTerm+" "+document.ignoreForm.bool2.value+" "+document.ignoreForm.query3.value;
	}
	document.frmQuick.$$.value = searchTerm;
	document.frmQuick.submit();
}

//	######################################################
//	The bunch of functions below are taken from scran_scripts_display.js
//	They allow the use of js code in the learning_materials section
//	dialogs section ****************
//	set global variables ***********

var dlgWindow, dlgArgs, dlgWidth, dlgHeight, dlgLeft, dlgTop, dlgScrolls, dlgResize ;

var dlgTools   =  '0' ;
var dlgMenus   =  '0' ;
var dlgLocs    =  '0' ;
var dlgStatus  =  '0' ;
var whichDlg   =  '' ;

var screenAvailWidth  =  parseInt(screen.availWidth)  ;
var screenAvailHeight =  parseInt(screen.availHeight) ;
var screenWidth  =  parseInt(screen.width)  ;
var screenHeight =  parseInt(screen.height) ;



//	sets dialog features
function dlgFeatures(dlgId) {
	switch (dlgId) {
		case 'loginDlg'		:  ((dlgWidth =  320)  &&  (dlgHeight =  140)  &&  (dlgScrolls =  '0')	&&  (dlgResize='no')) ;  break ;
		case 'helpDlg'		:  ((dlgWidth =  540)  &&  (dlgHeight =  460)  &&  (dlgScrolls =  '1')	&&  (dlgResize='no')) ;  break ;
		case 'nonStrdDlg'	:  ((dlgWidth =  540)  &&  (dlgHeight =  460)  &&  (dlgScrolls =  '1')	&&  (dlgResize='yes')) ;  break ;
		case 'standardDlg'	:  ((dlgWidth =  540)  &&  (dlgHeight =  460)  &&  (dlgScrolls =  '1')	&&  (dlgResize='yes')) ;  break ;
		case 'controlDlg'	:  ((dlgWidth =  445)  &&  (dlgHeight =  460)  &&  (dlgScrolls =  '1')	&&  (dlgResize='yes')) ;  break ;
		case 'albumDlg'		:  ((dlgWidth =  600)  &&  (dlgHeight =  400)  &&  (dlgScrolls =  '1')	&&  (dlgResize='yes')) ;  break ;
		case 'roymapDlg'	:  ((dlgWidth =  600)  &&  (dlgHeight =  400)  &&  (dlgScrolls =  '1')	&&  (dlgResize='yes')) ;  break ;
		}
	
		return dlgWidth ;
		return dlgHeight ;
		return dlgScrolls ;
		return dlgResize ;
}


//	positions dialogs
function dlgPos(dlgWidth,dlgHeight) {
	dlgLeft =  Math.floor((screenAvailWidth  - dlgWidth)  / 2) ;
	dlgTop  =  Math.floor((screenAvailHeight - dlgHeight) / 2) ;
	
	return dlgLeft ;
	return dlgTop ;
}


//	creates dialog and extra windows for website
function dlgCreate(dlgId,dlgUrl) {
	dlgFeatures(dlgId);
	dlgPos(dlgWidth,dlgHeight,dlgLeft,dlgTop);
	
	dlgArgs = ('width=' +dlgWidth+ ',height=' +dlgHeight+ ',left=' +dlgLeft+ ',top=' +dlgTop+ ',scrollbars=' +dlgScrolls+ ',toolbar=' +dlgTools+ ',menubar=' +dlgMenus+ ',location=' +dlgLocs+ ',status=' +dlgStatus+ ',resizable=' +dlgResize);
	
	dlgWindow = window.open(dlgUrl,dlgId,dlgArgs);
	dlgWindow.focus();
}


//	-----------------------------------------

// the 3 functions below are for checking form fields (caption comp. form)
function validRequired(formField,fieldLabel) {
	var result = true;
	
	if (formField.value == "") {
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	
	return result;
}

function validEmail(formField,fieldLabel,required) {
	var result = true;
	
	if (required && !validRequired(formField,fieldLabel)) {
		result = false;
	}
	
	if ( !required && formField.value == "") {
		return true;
	} else {
		if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) )	{
			alert("Please enter a complete email address in the form: yourname@yourdomain.com");
			formField.focus();
			result = false;
		}
	}
	return result;

}

function validateCaptionForm(theForm) {
	// Customize the form fields to check
	if (!validRequired(theForm.caption,"caption"))	return false;
	if (!validRequired(theForm.name,"name"))		return false;
	if (!validRequired(theForm.email,"e-mail"))		return false;
	if (!validEmail(theForm.email,"email",false))	return false;
	
	return true;
}

// Search for and highlight a string in a textarea specified by id
function findInTextarea(textareaid, needle) {
	if (document.getElementById) {
		if (document.getElementById(textareaid)) {
			var box = document.getElementById(textareaid);
			//document.getElementById(textareaid).focus();
			var position = -1;
			if ((box.selectionStart > 0) && (box.selectionStart < box.textLength)) {
				position = box.selectionStart + 1;
				//alert(position);
			}
			var atest = 0;
			var i;
			
			atest = box.value.indexOf(needle, position);
			
			if (position > 0 && atest == -1) {
				position = box.value.indexOf(needle, 0);
			} else {
				position = atest;
			}
			if (position > -1) {
				box.focus();
				//alert(needle.length);
				
				box.selectionStart = position;
				box.selectionEnd = position + needle.length;
				//alert(position);
			} else {
				alert(needle + " not found");
			}
		}
	}
}

// change text box background and tick a "save this" tickybox simultaneously
function fieldchanged(fieldobject, tickboxid) {
	//var obj = crossbrowser_return_documentobject(fieldid);
	var box = crossbrowser_return_documentobject(tickboxid);
	if (fieldobject && box) {
		fieldobject.style.background='#ffffdd';
		box.checked = true;
	}
}

function collectionorderdropdownchange(changedobjectid, objectoldvalue, arrayofobjects) {
	
	//alert(arrayofobjects);
	
	var dropdownprefix = 'collection_items_link_order';
	var tickboxprefix = 'savecollection_item';
	
	var dropdown = crossbrowser_return_documentobject(dropdownprefix + changedobjectid);
	var tickbox = crossbrowser_return_documentobject(tickboxprefix + changedobjectid);
	
	var newvalue = parseInt(dropdown.value, 10);
	var oldvalue = parseInt(objectoldvalue, 10);
	
	
	if ((isNaN(newvalue) == false) && (newvalue != oldvalue)) {
		
		var anidnumber;
		
		if (newvalue > oldvalue) {
			for (x in arrayofobjects) {
				var anidnumber = arrayofobjects[x];
				var adropdown = crossbrowser_return_documentobject(dropdownprefix + anidnumber);
				var adropdownvalue = parseInt(adropdown.value, 10);
				if ((adropdownvalue > oldvalue) && (adropdownvalue <= newvalue)) {
					adropdown.value = --adropdownvalue;
					fieldchanged(adropdown, tickboxprefix + anidnumber);
				}
			}
			dropdown.value = newvalue;
		} else if (newvalue < oldvalue) {
			for (x in arrayofobjects) {
				var anidnumber = arrayofobjects[x];
				var adropdown = crossbrowser_return_documentobject(dropdownprefix + anidnumber);
				var adropdownvalue = parseInt(adropdown.value, 10);
				if ((adropdownvalue < oldvalue) && (adropdownvalue >= newvalue)) {
					adropdown.value = ++adropdownvalue;
					fieldchanged(adropdown, tickboxprefix + anidnumber);
				}
			}
			dropdown.value = newvalue;
		}
		
		
	}
	
}

function textareaheightalter(objectid, direction) {
	var box = crossbrowser_return_documentobject(objectid);
	if (objectid && box) {
		if (!initialheights[objectid]) {
			initialheights[objectid] = box.clientHeight;
		}
		if (direction == 'inc') {
			//alert(box.clientHeight);
			var newheight = box.clientHeight + initialheights[objectid];
			box.style.height = newheight + 'px';
		} else if (direction == 'dec') {
			if (box.clientHeight >= (initialheights[objectid] * 2)) {
				var newheight = box.clientHeight - initialheights[objectid];
				box.style.height = newheight + 'px';
			} else {
				box.style.height = initialheights[objectid] + 'px';
			}
		}
	}
}

/* ######################################################################### */

//script for contribution repating feilds? 
function addEvent(type) {
	var ni = document.getElementById(type);
	var numi = document.getElementById('no_'+type);
	var num = (document.getElementById("no_"+type).value -1)+ 2;
	numi.value = num;
	var divIdName = type+num;
	var newdiv = document.createElement('div');
	newdiv.setAttribute("id",divIdName);
	switch(type){
		case "whats":
			newdiv.innerHTML = "<label for='"+divIdName+"'></label><input type='text' name='"+divIdName+"'/>&nbsp;<a href=\"javascript:;\" onclick=\"removeEvent(\'"+type+"\', \'"+divIdName+"\')\"> - Remove</a>";
		break;
		case "wheres":
			newdiv.innerHTML = "<label for='"+divIdName+"'></label><input type='text' name='"+divIdName+"'/>&nbsp;<input type='text' name='type"+divIdName+"'/>&nbsp<input type='text' size ='9' name='northing"+divIdName+"'/>&nbsp<input type='text' size ='9' name='easting"+divIdName+"'/><a href=\"javascript:;\" onclick=\"removeEvent(\'"+type+"\', \'"+divIdName+"\')\"> - Remove";
		break;
		case"whens":
			newdiv.innerHTML = "<label for='"+divIdName+"'></label><input type='text' name='"+divIdName+"'/>&nbsp;<input type='text' name='type"+divIdName+"'/><a href=\"javascript:;\" onclick=\"removeEvent(\'"+type+"\', \'"+divIdName+"\')\"> - Remove</a>";
		break;
		case"whos":
			newdiv.innerHTML = "<label for='"+divIdName+"'></label><input type='text' name='"+divIdName+"'/>&nbsp;<input type='text' name='type"+divIdName+"'/><a href=\"javascript:;\" onclick=\"removeEvent(\'"+type+"\', \'"+divIdName+"\')\"> - Remove</a>";
		break;
		case"refs":
			newdiv.innerHTML = "<label for='"+divIdName+"'></label><input type='text' name='title"+divIdName+"'/>&nbsp;<input type='text' name='titlelink"+divIdName+"'/>&nbsp;<input type='text' name='authour"+divIdName+"'/><a href=\"javascript:;\" onclick=\"removeEvent(\'"+type+"\', \'"+divIdName+"\')\"> - Remove </a>";
		break;
		default:
	}
	
	ni.appendChild(newdiv);
}

function removeEvent(type,divNum,delid) {
	var d = document.getElementById(type);
	var olddiv = document.getElementById(divNum);
	d.removeChild(olddiv);
	
	if (delid != undefined) {
		var ni = document.getElementById(type);
		var newdiv = document.createElement('div');
		newdiv.setAttribute("id",divNum);
		newdiv.innerHTML = "<input type='hidden' name='id"+divNum+"' value='"+delid+"' />";
		ni.appendChild(newdiv);
	}
}

/* ######################################################################### */

//andy's tagging
function toggleTag(tag, input) {
	
	var link = crossbrowser_return_documentobject(tag);
	var input = crossbrowser_return_documentobject(input);
	
	if (input && (!input.disabled || input.enabled)) {
		if (input.checked) {
			input.checked = false;
		} else {
			input.checked = true;
		}
	}
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds){
			return;
		}
	}
}


