//-- basic functions

function setCookie( name, value, hours )
{
	document.cookie = name + "=" + escape( value )
		+ ((hours)?(";expires=" + ((new Date((new Date()).getTime() + parseInt(hours)*3600000)).toGMTString())):";");
}

function getCookie( name )
{
	var rg = new RegExp(name + "=([^;]+)");
	var cv = rg.exec(document.cookie);
	return ( cv != null ) ? unescape( cv[ 1 ] ) : null;
}

function killCookie( name )
{
	document.cookie = name + "=;expires=Fri, 13-Apr-1977 00:00:00 GMT";
}

//-- other useful functions

function textFromCookie( field, cookiename )
{
	var cookieValue = getCookie( cookiename );
	if ( cookieValue ) {
		field.value = cookieValue;
	}
}

function stringToHTML( content ) {
	if( content != null )
		return content.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/\r\n/g,'<br>').replace(/[\r\n]/g,'<br>');
	else
		return "";
}

function displayCookie( name )
{
	var cookieValue = getCookie( name );
	if ( cookieValue ) {
		document.write( stringToHTML( cookieValue ) );
	}
}

function killCookies( )
{
	for ( var i = 0; i < killCookies.arguments.length; i++ )
		killCookie( killCookies.arguments[ i ] );
}

//-- "back button" deterant

function setNoBackFlag( )
{
	setCookie( 'noback', 'true', 0 );
}

function clearNoBackFlag( )
{
	killCookie( 'noback' );
}


function enforceNoBackFlag( backToURL )
{
	if ( getCookie( 'noback' ) != null ) {
		alert( "You can no longer go back and change your initial responses." );
		window.location.href = backToURL;	
	}
}

//--- goto URL on condition of a number of words in a string

function ifEnoughGotoURL( checkText, numWords, url )
{
	if ( checkText != null ) {

		var results = checkText.split( /\s+/ );

		if ( results != null && results.length >= numWords ) {
			window.location.href = url;
			return;
		}
	}

	alert( 'More detail is required in your response.\rPlease provide this before moving on.' );
}

//--- date and timing stuff

function displayDate()
{
	var today = new Date();
	document.write( today.getDate() + "/" + (today.getMonth()+1) + "/" + today.getFullYear() );
}

function clearTiming()
{
	killCookies( 'startTime', 'endTime' );
}

function startTiming()
{
	setCookie( 'startTime', new Date(), 0 );
}

function endTiming()
{
	setCookie( 'endTime', new Date(), 0 );
}

function displayTimeTaken()
{
	var startTimeText = getCookie( 'startTime' );
	var endTimeText = getCookie( 'endTime' );

	if ( startTimeText == null || endTimeText == null )
		return;

	var startTime = new Date( startTimeText ).getTime() / 60000;
	var endTime = new Date( endTimeText ).getTime() / 60000;

	document.write( Math.round( endTime - startTime ) );
}
