////////////////////////////////////////////////////////////////////////////
// Global variables
////////////////////////////////////////////////////////////////////////////
// Misc. global variables.
nav = eval(navigator.appVersion.substring(0,1));
var	MAX_RECORDS		= 50;
var	nSecondsInADay		= 60 * 60 * 24;
var	nMilliSecondsInADay	= nSecondsInADay * 1000;
//
// Global variables associated with the un/select icons.
//
var	sUnselectedImageIcon	= "/images/add_off.gif";
var	sUnselectedImageAlt	= "add to list of selected records";
var	sSelectedImageIcon	= "/images/add_on.gif";
var	sSelectedImageAlt	= "remove from list of selected records";
//
// Global variables used for selected records comments.
//
var     nMaxCommentLength       = 1200;
var     bCommentsChanged        = false;
////////////////////////////////////////////////////////////////////////////
// Support functions
////////////////////////////////////////////////////////////////////////////
function cookiesEnabled()
{
	var	bEnabled	= true;
	var	sAllCookies	= this.document.cookie;
	
	if("" == sAllCookies)
	{
		alert("Please make sure that your browser has cookies enabled");
		bEnabled = false;
	}
	return bEnabled;
}

function cookieRead(sCookieName)
{
	var	sAllCookies	= this.document.cookie;
	var	nStart		= sAllCookies.indexOf(sCookieName);
	var	nEnd		= -1;
	var	sCookie		= "";
	
	if(-1 != nStart)
	{
		nEnd = sAllCookies.indexOf(";", nStart);
		if(-1 == nEnd)
		{
			nEnd = sAllCookies.length;
		}
		sCookie = sAllCookies.substring(nStart, nEnd);
		nStart = sCookie.indexOf("=") + 1;
		sCookie = sCookie.substring(nStart, sCookie.length);
	}
	return sCookie;
}

//function cookieWrite(sCookieName, sCookieValue)
//{
//	var	sCookiePath		= " path=/;";
//	var	dExpires		= new Date();
//	var	sCookieExpiry		= "";
//	var	sCookie			= "";
//
//	if(0 == sCookieValue.length)
//	{
//		dExpires.setTime(0);
//	}
//	else
//	{
//		var	dToday = new Date();
//		dExpires.setTime(dToday.getTime() + (nMilliSecondsInADay * 90));
//	}
//
//	sCookieExpiry = " expires=" + dExpires.toGMTString() + ";";
//	sCookie += sCookieName + "=" + sCookieValue + ";" + sCookiePath + sCookieExpiry;
//	this.document.cookie = sCookie;
//}
function cookieWrite(sCookieName, sCookieValue)
{
	var	sCookiePath		= " path=/;";
	var	dExpires		= new Date();
	var	sCookieExpiry		= "";
	var	sCookie			= "";

	if(0 == sCookieValue.length)
	{
		dExpires.setTime(0);
		sCookieExpiry = " expires=" + dExpires.toGMTString() + ";";
	}

	sCookie += sCookieName + "=" + sCookieValue + ";" + sCookiePath + sCookieExpiry;
	this.document.cookie = sCookie;
}

//
// We may not have the luxury of sString.split(...) in which case
// we'll have to do it the longhanded way.
//
function stringSplit(sString, sSplit)
{
	var	sStringTemp	= new String(sString);
	var	aString		= new Array();

	if("" == sStringTemp)
	{
		// Well, its an empty string!!
	}
	else if(-1 == sStringTemp.indexOf(sSplit))
	{
		aString[0] = sStringTemp;
	}
	else
	{
		if(sStringTemp.split)
		{
			aString = sStringTemp.split(sSplit);
		}
		else
		{
			var	nStart	= -1;
			var	nEnd	= sStringTemp.indexOf(sSplit);
			var	nIndex	= 0;

			if(sStringTemp.split)
			{
				aString = sStringTemp.split(sSplit);
			}
			else
			{
				while(sStringTemp.indexOf(sSplit, nStart + 1) != -1)
				{
					aString[nIndex] = sStringTemp.substring(nStart + 1, nEnd);
					nIndex++;
					nStart = nEnd;
					nEnd = sStringTemp.indexOf(sSplit, nStart + 1);	
	
					if(-1 == nEnd)
					{
						nEnd = sStringTemp.length;
					}
				}
				nStart = sStringTemp.lastIndexOf(sSplit);
				nEnd = sStringTemp.length;
				aString[nIndex] = sStringTemp.substring(nStart + 1, nEnd);
			}
		}
	}
	return aString;
}

function stringReplace(sString, sReplace, sWith)
{
	var	sStringTemp	= new String(sString);
	var	sStringNew	= new String("")
	var	nStart		= 0;
	var	nIndex		= 0;

	while(-1 != (nIndex = sStringTemp.indexOf(sReplace, nStart)))
	{
		sStringNew += sStringTemp.substring(nStart, nIndex);
		sStringNew += sWith;
		nStart = nIndex + sReplace.length;
	}
	sStringNew += sStringTemp.substring(nStart, sStringTemp.length);

	return sStringNew;
}

function stringCmp(sFirst, sSecond)
{
	var	nResult	= 0;
	if(sFirst.length > sSecond.length)
	{
		nResult = 1;
	}
	else if(sFirst.length < sSecond.length)
	{
		nResult = -1;
	}
	
	for(var i = 0; (0 == nResult) && (i < sFirst.length); i++)
	{
		if(sFirst.charAt(i) > sSecond.charAt(i))
		{
			nResult = 1;
		}
		else if(sFirst.charAt(i) < sSecond.charAt(i))
		{
			nResult = -1;
		}
	}

	return nResult;
}

//
// This is a bit horrific. IE wasn't a problem, however, under Netscape the
// document.anchors[i].href property is undefined and there's no obvious way 
// of matching up anchors and links. So here we run through all the links
// trying to find the one which mentions the right offset and cookie combo.
//
function fnFindLink(sCookieName, sOffset)
{
	var	nLink		= -1;

	for(var i = 0; (-1 == nLink) && (i < document.links.length); i++)
	{
		var	sHREF	= new String(document.links[i].href);
		if((-1 != sHREF.indexOf("'" + sOffset + "'")) && (-1 != sHREF.indexOf(sCookieName)))
		{
			nLink = i;
		}
	}
	return nLink;
}

function fnSelect(sCookieName, sOffset, bSelect)
{
	var     sImageName      = "sel" + sOffset;
	var	nLink		= -1;

	nLink = fnFindLink(sCookieName, sOffset);

	if(-1 != nLink)
	{
		if(bSelect)
		{
			var sNewLink = stringReplace(document.links[nLink].href, 'add', 'remove');
			document.links[nLink].href = sNewLink;
			document[sImageName].src = sSelectedImageIcon;
			document[sImageName].alt = sSelectedImageAlt;
		}
		else
		{
			var sNewLink = stringReplace(document.links[nLink].href, 'remove', 'add');
			document.links[nLink].href = sNewLink;
			document[sImageName].src = sUnselectedImageIcon;
			document[sImageName].alt = sUnselectedImageAlt;
		}
	}
}
////////////////////////////////////////////////////////////////////////////
// Externally used functions
////////////////////////////////////////////////////////////////////////////
function fnCheckForSelectedRecords(sCookieName)
{
	if(cookiesEnabled())
	{
		var     sCookie         = cookieRead(sCookieName);
		var     aDBOffsets      = new Array();

		aDBOffsets = stringSplit(sCookie, "|");

		for(var i = 0; i < aDBOffsets.length; i++)
		{
			fnSelect(sCookieName, aDBOffsets[i], true);
		}
	}
}

function addRecord(sDBOffset, sCookieName, bAddingAll)
{
	var	bAdded		= false;

	if(cookiesEnabled())
	{
		var	sCookie		= cookieRead(sCookieName);
		var	sCookieNew	= "";
		var	aDBOffsets	= new Array();
		var	bAlreadyExists	= false;
		
		aDBOffsets = stringSplit(sCookie, "|");

		//
		// Check to see if this offset already exists in the list.
		//
		for(var i = 0; i < aDBOffsets.length; i++)
		{
			if(aDBOffsets[i] == sDBOffset)
			{
				bAlreadyExists = true;
				continue;
			}
		}
		
		//
		// Check to see if adding this record will exceed the maximum limit.
		//
		if(MAX_RECORDS <= aDBOffsets.length)
		{
		    alert("You can only select a maximum of " + MAX_RECORDS +" records.\nTry clearing some selected records.");
		}
		else if((sCookie != sDBOffset) && (false == bAlreadyExists))
		{
			if(0 == sCookie.indexOf("undefined"))
			{
				cookieWrite(sCookieName, sDBOffset);
			}
			else
			{
				//
				// Insert the db offset in the correct place numerically.
				//
				var	bDone		= false;
				var	nDBOffset	= parseInt(sDBOffset);
				var	j		= 0;

				//
				// Loop to find the suitable spot for the new value.
				// Appending existing values as we go.
				//
				while((false == bDone) && (j < aDBOffsets.length))
				{
					// N.B. need to convert string to int before we make comparison.
					if(1 > stringCmp(aDBOffsets[j], sDBOffset))
					{
						sCookieNew += aDBOffsets[j];
						sCookieNew += "|";
						j++;
					}
					else
					{
						bDone = true;
					}
				}

				//
				// Now append our new value.
				//
				sCookieNew += sDBOffset;
				bAdded = true;

				//
				// Then add the rest of the existing values carrying on from
				// where we left off.
				//
				while(j < aDBOffsets.length)
				{
					sCookieNew += "|";
					sCookieNew += aDBOffsets[j];
					j++;
				}
				
				cookieWrite(sCookieName, sCookieNew);
			}
		}
		
		if(bAdded)
		{
//			if(2 > nav)
//			{
				fnSelect(sCookieName, sDBOffset, true);
//			}

//			if (!bAddingAll)
//			{
//				alert("This record has been added to your list of Selected Records.");
//			}
		}
	}
	
	if(bAddingAll)
	{
		return bAdded;
	}
}

function addAllRecords()
{
	if(0 == document.forms[1].length)
	{
		alert("There are no records for you to select.");
	}
	else if(cookiesEnabled())
	{
		var	nAdded		= 0;	// The number of the records we've added this time.
		var	nToBeAdded	= 0;	// Number of records to add.
		var	aDBOffsets;

		if(1 == document.forms[1].length)
		{
			var	aTemp		= document.forms[1].ADDALL.value.split("+");
			var	sCookie		= cookieRead(aTemp[1]);

			aDBOffsets	= stringSplit(sCookie, "|");
			nToBeAdded	= 1;

			if(aDBOffsets.length < MAX_RECORDS)
			{
				var	aValues	= document.forms[1].ADDALL.value.split("+");
				if(addRecord(aValues[0], aValues[1], true))
				{
					nAdded++;
				}
			}
		}
		else
		{
			var	i		= 0;
			var	aTemp		= document.forms[1].ADDALL[0].value.split("+");
			var	sCookie		= cookieRead(aTemp[1]);

			aDBOffsets	= stringSplit(sCookie, "|");
			nToBeAdded	= document.forms[1].ADDALL.length;

			do
			{
				var	aValues	= document.forms[1].ADDALL[i].value.split("+");
				if(addRecord(aValues[0], aValues[1], true))
				{
					nAdded++;
				}
				i++;
			}
			while(((nAdded + aDBOffsets.length) < MAX_RECORDS) && (i < document.forms[1].ADDALL.length))
		}		

		if (nAdded == nToBeAdded)
		{
			alert("All records on this page have been added.");
		}
		else if(0 < nAdded)
		{
			alert("Records " + aDBOffsets.length + " - " + (aDBOffsets.length + nAdded) + " have been added to your list of Selected Records.");
		}
		else
		{
			//alert("No records have been added to your list of Selected Records.");
		}
	}
}

function removeRecord(sDBOffset, sCookieName)
{
	// Removing the record from the cookie.
	if(cookiesEnabled())
	{
		var	sCookie		= cookieRead(sCookieName);
		var	aDBOffsets	= stringSplit(sCookie, "|");
		var	sCookieNew	= "";

		for(var i = 0; i < aDBOffsets.length; i++)
		{
			if(aDBOffsets[i] == sDBOffset)
			{
				fnSelect(sCookieName, sDBOffset, false);
			}
			else
			{
				if(0 < sCookieNew.length)
				{
					sCookieNew += "|";
				}
				
				sCookieNew += aDBOffsets[i];
			}
		}
			
		cookieWrite(sCookieName, sCookieNew);
	}
	
	if(true == bCommentsChanged)
	{
		document.comments.submit();
		alert("Your notes have been saved.");
	}
	
	//return true;
}

function clearAll(sCookieName)
{
	if(cookiesEnabled())
	{
		cookieWrite(sCookieName, "");
	}
	return true;
}

//
// Alert the user to the fact that they have made changes to their comments
// and they'll lose them if they carry on.
//
function fnCheckComments()
{
	if(true == bCommentsChanged)
	{
		return confirm("You will lose your notes if you navigate away from this page without saving them.\n\nTo save your notes click 'cancel' followed by the 'save notes' icon beside your notes.\nTo continue and discard your notes click 'OK'.");
	}
	return true;
}

//
// This sets the onClick() event for every link on the page
// so that the passed in function is called to decide
// the fate of the user's click.
//
// This function takes a function reference and an array of strings
// specifying substring which if present in HREFs mean the onClick should
// not be altered.
//	e.g.	fnTrapLinks(fnCheckComments, ['somtype=VIEWSELRECS']);
//
function fnTrapLinks(fnFunction, asExceptions)
{
	for(var i = 0; i < document.links.length; i++)
	{
		var	bException	= false;
		if(asExceptions && asExceptions.length)
		{			
			for(var j = 0; !bException && (j < asExceptions.length); j++)
			{
				var	sHREF	= new String(document.links[i].href);
				if(-1 != sHREF.indexOf(asExceptions[j]))
				{
					bException = true;
				}
			}
		}
		if(!bException)
		{
			document.links[i].onclick = fnFunction;
		}
	}
}

//
// This function should be called whenever a user presses a key whilst
// a textarea has focus. It allows us to limit the amount of text they
// enter as well as monitoring when changes have been made.
//
function fnCommentChanged(taComment)
{
	if(nMaxCommentLength <= taComment.value.length)
	{
		alert("Sorry, individual comments are limited to a maximum of " + nMaxCommentLength + " characters in length.");
		return false;
	}
	bCommentsChanged = true;
	return true;
}

function fnEmailDetailsSave()
{
	document.main.onSubmit	= "";
	document.main.action.value = "SearchOrBrowse";
	document.main.search.value = "emailselectedrecords";
	document.main.somtype.value = "EMAILSELRECS";
	document.main.submit();
}

function fnEmailDetailsClear()
{
	document.main.from.value = "";
	document.main.to.value = "";
	document.main.comment.value = "";
	fnEmailDetailsSave();
}

