// Replaces text with by in string
function replace(string,text,by) 
{
	if (string.length == 0) return string; 

	var re = new RegExp( text, 'g');
	return string.replace(re,by);
}
function trapError()
{
	return true;
}
function submitForm(destination)
{
	self.onerror = trapError;
	document.frm.Destination.value = destination;
	document.frm.submit();
	self.onerror = null;
}
function popupWindow(windowName, destination)
{
	var newWindow;
	newWindow = window.open(destination,windowName,'toolbar=o,location=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,width=1024,height=750');
}
function popupWindowSize(windowName, destination, x, y, w, h, showScrollbars, showMenu)
{
	var newWindow;
	newWindow = window.open(destination,windowName,'toolbar=no,location=no,directories=no,status=no,menubar='+showMenu+',scrollbars='+showScrollbars+',resizable=no,top='+y+',left='+x+',width='+w+',height='+h);
}
function popupWindowReSize(windowName, destination, x, y, w, h)
{
	var newWindow;
	newWindow = window.open(destination,windowName,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,top='+y+',left='+x+',width='+w+',height='+h);
}
function popupChart(windowName, destination, x, y, w, h)
{
	var newWindow;
	newWindow = window.open(destination,windowName,'toolbar=yes,location=no,directories=no,status=no,menubar=yes,scrollbars=no,resizable=yes,top='+y+',left='+x+',width='+w+',height='+h);
}
function setStatus(someText)
{
	window.status = someText;
}
function updateHighlight(whichField,fieldType)
{
	if (fieldType=='TXT')
	{
		if (whichField.value=='')
			whichField.className = 'InputText';
		else
			whichField.className = 'InputTextHighlight';
	}
	else if (fieldType=='CBO')
	{
		if (whichField.value=='')
		{
			//eval('document.all.'+whichField.name+'Span.className=\'InputText\'');
			whichField.className = 'InputText';				
		}
		else
		{
			//eval('document.all.'+whichField.name+'Span.className=\'InputComboHighlight\'');
			whichField.className = 'InputTextHighlight';
		}
	}
	else if (fieldType=='RADIO')
	{
		if (whichField.value=='')
			whichField.className = 'InputRadio';				
		else
			whichField.className = 'InputRadioHighlight';
	}
	else if (fieldType=='CHECKBOX')
	{
		if (whichField.checked)
			whichField.className = 'InputCheckboxHighlight';
		else
			whichField.className = 'InputCheckbox';
	}
}

function copyToClipboard(value)
{
	clipboardData.setData("Text",value);
}

var nTimeout = 0;

function showMenu(menuObj,anchorObj,offsetX,offsetY)
{
	moveRelativeTo(menuObj,anchorObj,offsetX,offsetY);
/*
	var xywhLink = getPageXY(lnkObj);
	var xywhMenu = getPageXY('studiesMenu');
	
	shiftTo('studiesMenu', xywhLink.x, xywhLink.y+xywhLink.h+3);		
*/	
	document.all.studiesMenu.style.visibility = 'visible';

	document.all.helpFrame.style.left = parseInt(document.all.studiesMenu.style.left);
	document.all.helpFrame.style.top = parseInt(document.all.studiesMenu.style.top);
	document.all.helpFrame.style.width = document.all.studiesMenu.clientWidth;
	document.all.helpFrame.style.height = document.all.studiesMenu.clientHeight;
	document.all.helpFrame.style.visibility = 'visible';

	//setTimeout('setFrameSize(\'studiesMenu\',0,0,0,0)',1);
}

function hideMenu()
{
	document.all.studiesMenu.style.visibility = 'hidden';
	document.all.helpFrame.style.visibility = 'hidden';
	//hideShowLayer('studiesMenu','hidden');
	//hideShowLayer('layerFrame','hidden');
	nTimeout = 0;
}

function resultGroupClicked(obj,title)
{
	if(obj.className=='collapsed')
	{
		obj.className='expanded'; 
		document.getElementById(title+'submenu').style.display='block';
		document.getElementById(title+'expanded').value='yes';
	}
	else
	{
		obj.className='collapsed'; 
		document.getElementById(title+'submenu').style.display='none';
		document.getElementById(title+'expanded').value='';
	}
}

function getWindowDimensions()
{
	d=document
	if (typeof window.innerWidth!='undefined') 
	{
		var winWidth = window.innerWidth;
		var winHeight = window.innerHeight;
	} 
	else 
	{
		if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0)
		{
			var winWidth = d.documentElement.clientWidth
			var winHeight = d.documentElement.clientHeight
		} 
		else 
		{
			if (d.body && typeof d.body.clientWidth!='undefined') 
			{
				var winWidth = d.body.clientWidth
				var winHeight = d.body.clientHeight
			}
		}
	}
	
	return {width:winWidth,height:winHeight};
}


var startTime;
function startTimer() 
{
	var dToday = new Date();
	startTime = dToday.getTime();	
}

var endTime;
function endTimer()
{
	var diff;
	var dToday = new Date();	
	endTime = dToday.getTime();	
	diff = (endTime - startTime)/1000;	//compute elapsed time
	return diff;
}

function changeStyleByObj(obj,styleChanges)
{
	var aChanges = styleChanges.split('|');
	for (var i=0; i<aChanges.length; i++) 
	{
		var styleChange = aChanges[i].split(':');
		eval('obj.style.'+styleChange[0]+' = \''+styleChange[1]+'\'');
	}	
}

function changeStyleByID(objID,styleChanges)
{
	var obj = document.getElementById(objID);
	var aChanges = styleChanges.split('|');
	var currentValue;
	
	for (var i=0; i<aChanges.length; i++) 
	{
		var styleChange = aChanges[i].split(':');
		eval('obj.style.'+styleChange[0]+' = \''+styleChange[1]+'\'');
	}	
}

function dom(id) {
	return document.getElementById(id);
}

/*
 * -- NEW CODE START --
 */
var Key = {
	_shiftPressed: null,
	keydown: function( KeyStroke ) {
		var oKeyboardEvent = KeyStroke || window.event;
		Key._shiftPressed = (oKeyboardEvent.shiftKey == true);
	},
	keyup: function() {
		Key.reset();
	},
	reset: function() {
		this._shiftPressed = false;
	},
	isShift: function() {
		return this._shiftPressed;
	}
};

var bCheckSelected = true;
var oLastSelected = { ticked: true, rowNum: null, wellID: null };

function GetLastSelectedDetails( wellID ) {
	if ( wellID == '' ) {
		oLastSelected = { ticked: true, rowNum: null, wellID: null };
		return false;
	}
		
	var oTD = document.getElementById('ws' + wellID).parentNode.parentNode;
	var nRowNumber = Number( oTD.id.replace(/first/g,'') );
	
	if ( bCheckSelected ) {
		if ( Key.isShift() && oLastSelected.rowNum != null ) {
			if ( nRowNumber > oLastSelected.rowNum )
				selectWellRange( oLastSelected.rowNum + 1, nRowNumber );
			else
				selectWellRange( nRowNumber + 1, oLastSelected.rowNum );
		}
	}
	
	oLastSelected.ticked = ( document.getElementById( 'ws' + wellID ).src.indexOf( 'chk1' ) != -1 );
	oLastSelected.rowNum = nRowNumber;
	oLastSelected.wellID = wellID;
}

function selectWellRange( StartRowNumber, EndRowNumber ) {
	bCheckSelected = false;
	var aWellID = new Array();
	
	for (var i = StartRowNumber; i < EndRowNumber; i++) {
		var nWellId = document.getElementById( 'first' + i ).parentNode.id.replace( /row/, '' );
		
		// If the start well was ticked, then ticked all other wells to the end selection and vice versa for not ticked wells.
		if ( (oLastSelected.ticked && !isWellTicked( nWellId )) || (!oLastSelected.ticked && isWellTicked( nWellId )) ) {
			//selectWell( nWellId );
			aWellID.push( nWellId );
		}
	}
	
	$.ajax( {
		url : 'includes/selectWellRange.asp?study='+study+'&wellID='+aWellID.join() + '&ticked='+oLastSelected.ticked,
		success : function( html, status ) {
			var result = eval('(' + html + ')');
		
			var aChangedWells = result.wellsChanged.split( ',' );
			
			for ( var i = 0; i < aChangedWells.length; i++ ) {
				if ( dom('ws'+aChangedWells[i]) ) {
					if ( oLastSelected.ticked ) {
						dom('ws'+aChangedWells[i]).src = 'images/chk2.gif';
						dom('row'+aChangedWells[i]).className = 'tableRowSelected';
					}
					else {
						dom('ws'+aChangedWells[i]).src = 'images/chk1.gif';
						dom('row'+aChangedWells[i]).className = dom('row'+aChangedWells[i]).getAttribute('oldClass');
					}
				}
			}
		},
		async : false
	} );
	
	bCheckSelected = true;
}

function isWellTicked( wellId ) {
	return ( document.getElementById( 'ws' + wellId ).src.indexOf( 'chk2' ) != -1 );
}

function FindObjectsByTag( TagName, ParentNode, ReturnFirst ) {
	var aReturnVal = new Array();

	for ( var i = 0; i < ParentNode.length; i++ ) {
		if ( ParentNode[i].tagName == TagName ) {
			if ( ReturnFirst )
				return ParentNode[i];
			else
				aReturnVal[aReturnVal.length] = ParentNode[i];
		}
	}

	return (aReturnVal.length == 0 ? null : aReturnVal);
}
/*
 * -- NEW CODE END -- 
 */

// an associative array to hold the select wells details
// for each study
var aSelectedWells = new Array();

// 25-08-2008
// function added to handle selecting and deselecting wells
// calls the server to maintain the list of selected well ID's
// If we don't pass a well to the server, it will clear the list
function selectWell(wellID) {
	GetLastSelectedDetails( wellID );
	
	fetchPage('','includes/selectWells.asp','study='+study+'&wellID='+wellID,function(result) {
		if (result=='TIMEOUT')
			document.location='../..index.asp?err=timeout';
		else {
			// hide any popups (performance metrics/charts)
			if (dom('MetricsDiv'))
				dom('MetricsDiv').style.visibility = 'hidden';
			dom('helpFrame').style.visibility = 'hidden';
			dom('createChart').style.display = 'none';
			
			result = eval('(' + result + ')');
	
			// ensure study is lowercase before accessing array
			//study = study.toLowerCase();
			
			// remember the value of filtered before replacing
			var filtered = aSelectedWells[study].filtered;
			
			// store the current selected wells details so
			// other parts of the site can access it.
			aSelectedWells[study] = result;
			aSelectedWells[study].filtered = filtered;
			
			if (result.wellAdded) {
				// well has been added to list and needs to be selected
				dom('ws'+wellID).src = 'images/chk2.gif';
				dom('row'+wellID).className = 'tableRowSelected';
				highlightFirstColumn(false);
			}
			else {
				if (wellID=='') {
					// clear all ticks on the current page
					var IDs = result.listBefore.split(',');
					for (var n=1; n<IDs.length-1; n++) {
						// check to make sure the selected well is on the current page
						if (dom('ws'+IDs[n])) {
							// it is, so we deselect it
							dom('ws'+IDs[n]).src = 'images/chk1.gif';
							dom('row'+IDs[n]).className = dom('row'+IDs[n]).getAttribute('oldClass');
						}
					}
				}
				else {
					// well has been removed from list and needs to be deselected
					dom('ws'+wellID).src = 'images/chk1.gif';
					dom('row'+wellID).className = dom('row'+wellID).getAttribute('oldClass');
				}
				
				if (result.listIsEmpty) {
					// reset column back to normal by telling the function to 
					// use the initial styling
					highlightFirstColumn(true);				
				}
			}
			
			// update the results title
			if (result.count==0) {
				dom('resultsTitle').innerHTML = numWellsAvailable+'&nbsp;'+(study=='DPR'?'wells':'completions');
				dom('informationTooltip').style.display = 'none';
			}
			else {
				dom('resultsTitle').innerHTML = result.count+'&nbsp;of&nbsp;'+numWellsAvailable+'&nbsp;'+(study=='DPR'?'wells':'completions')+'&nbsp;are&nbsp;selected';
				dom('informationTooltip').style.display = 'block';
			}
																					  }
	});
}

// function that each of the special areas call before allowing entry
function checkIfNoWellsAreSelected(specialArea) {
	if (aSelectedWells[study]) {
		if (aSelectedWells[study].count==0)
			// no wells are selected so we can proceed
			return true;
		else {
			if (aSelectedWells[study].count == numWellsAvailable) {
				// if all wells are selected we allow user to proceed, but
				// warn them that it's not necessary to select all wells.
				alert('You have selected (ticked) every well in the search results.\n\nThis is not necessary and the ticks have been ignored.\n\nUse the "Select wells" column if you wish to exclude some\nwells from the '+specialArea+'.');
				return true;
			}
			else {
				// if some wells are selected the the user
				// is told to decide what do to about them first
				// before proceeding.
				alert('You have selected (ticked) some wells on the search results page.\n\nYou have not indicated whether wells are to be excluded from\nthe '+specialArea+'.\n\nPlease click the "select wells" column heading and choose one of\nthe options.');
				return false;
			}
		}
	}
	else
		// no wells have been selected yet as 
		// the structure has not been created yet.
		return true;
}

function showWellSelectionMenu(obj) {
	var bShowMenu = true;
	
	if (aSelectedWells[study].count==0)
		if (aSelectedWells[study].filtered) {
			dom('disabledPartsOfWellSelectionMenu1').style.display='block'
			dom('disabledPartsOfWellSelectionMenu2').style.display='none'
			dom('enabledPartsOfWellSelectionMenu').style.display='none'
		}
		else {
			alert('Use this column if you wish to exclude wells from the search results page.\n\nYou can either select (tick) the wells you want to exclude\nor select the wells you want left in and exclude the rest.\n\nHold down the shift key to select a set of wells on this page.');
			bShowMenu = false;
		}
	else {
		dom('disabledPartsOfWellSelectionMenu1').style.display='none'
		dom('disabledPartsOfWellSelectionMenu2').style.display='none'
		dom('enabledPartsOfWellSelectionMenu').style.display='none'
		if (aSelectedWells[study].count == numWellsAvailable)
			dom('disabledPartsOfWellSelectionMenu2').style.display='block'
		else
			dom('enabledPartsOfWellSelectionMenu').style.display='block'
	}
	
	if (bShowMenu) {
		var objXYWH = getPageXYWH(obj);
		dom('wellSelectionMenu').style.top = (objXYWH.y+34)+'px';
		dom('wellSelectionMenu').style.display='block'
	}
}

// if any wells are selected, even if not on same page, the first column is to be highlight to
// indicate this.
function highlightFirstColumn(revertToOriginal) {
	var nRows = parseInt(dom('RowsPerPage').value);
	for (var row=1; row<=nRows; row++) {
		// check to make sure row exists
		if (dom('first'+row)) {
			if (revertToOriginal)
				dom('first'+row).className = dom('first'+row).getAttribute('oldClass');
			else
				dom('first'+row).className = dom('first'+row).getAttribute('oldClass')+' tableRowSelected';
		}
	}
}
var hideTimeout = null;
function hideSelectWellsMenu() {
	hideTimeout = setTimeout('dom(\'wellSelectionMenu\').style.display=\'none\'',500);
}

function sync() {
	dom('ColumnHeader').scrollLeft = dom('SearchResults').scrollLeft;
	dom('informationTooltip').scrollLeft = (dom('SearchResults').scrollLeft);
//	document.all.ColumnHeader.scrollLeft=document.all.SearchResults.scrollLeft;
}
//Change a class value from the default defined in the stylesheet
/*
function changeCSS(theClass,element,value) 
{
	var cssRules;
	if (document.all)
		cssRules = 'rules';
	else 
	{
		if (document.getElementById) 
			cssRules = 'cssRules';
	}

	for (var S = 0; S < document.styleSheets.length; S++)
	{
		for (var R = 0; R < document.styleSheets[S][cssRules].length; R++) 
		{
			if (document.styleSheets[S][cssRules][R].selectorText == theClass) 
			{
				document.styleSheets[S][cssRules][R].style[element] = value;
				return;
			}
		}
	}	
}
*/

function echeck(str) {
	var sExpression = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
		
	return str.match(sExpression) != null;
}