var xmlHttp;
var requestURL = '/ajax/?';
var siteURL = '/';
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;
var ajaxMemID, ajaxMsgID, ajaxReason, ajaxFieldName, ajaxFieldValue;
var lastClass = "table_dark_grey";
var lastProfileClass = "table_dark_grey";

// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url)
{
	
	xmlhttp.open('GET', url, true);
	xmlhttp.send(null);
}

// This function is based on a snippet from http://www.adahas.com/.  You saved our sanities! \o/  Have a cookie. :D
function replaceContent(elementID, xhtmlData)
{

	try
	{
		var elem = document.getElementById(elementID);
		var children = elem.childNodes;

		for (var i = 0; i < children.length; i++)
		{
			elem.removeChild(children[i]);
		}

		var nodes = new DOMParser().parseFromString(xhtmlData, 'application/xhtml+xml');
		var range = document.createRange();

		range.selectNodeContents(document.getElementById(elementID));
		range.deleteContents();

		for (var i = 0; i < nodes.childNodes.length; i++)
		{
			document.getElementById(elementID).appendChild(
			nodes.childNodes[i]);
		}
		return true;
	}
	catch (e1)
	{
		try
		{
			document.getElementById(elementID).innerHTML = xhtmlData;
			return true;
		}
		catch(e2)
		{
			alert("We are sorry, but your browser is not supported by Saga Zone.  Please use one of the following browsers:\n\n\t1) Microsoft Internet Explorer (http://www.microsoft.com/ie/)\n\t2) Mozilla Firefox (http://www.mozilla.com/firefox/)\n\t3) Opera (http://www.opera.com/)\n\t4) Safari (http://www.apple.com/safari/)\n\nWe apologise for any inconvenience that this may cause you.");
			return false;
		}
	}
}

var siteZone = 'P4542.SAG/saga_zone';
var kv = escape('');
var loc = escape(location.pathname);
var path = loc.substring(1).split('/');
var http;
var dfp_dcopt;

if (location.protocol == 'https:')
{
	sitezone = 'P4542.SAG/ssl';
	http = 'https:';
}
else
{
	http = 'http:';
}

function GetXmlHttpObject(handler)
{
	var objXmlHttp = null; //Holds the local xmlHTTP object instance

	//Depending on the browser, try to create the xmlHttp object
	if (is_ie)
	{
		//The object to create depends on version of IE
		//If it isn't ie5, then default to the Msxml2.XMLHTTP object
		var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';

		//Attempt to create the object
		try
		{
			objXmlHttp = new ActiveXObject(strObjName);
			objXmlHttp.onreadystatechange = handler;
		}
		catch(e)
		{
			//Object creation errored
			alert('AJAX initialisation failed; contact Digital.');
			return false;
		}
	}
	else
	{
		// Mozilla | Netscape | Safari
		objXmlHttp = new XMLHttpRequest();
		objXmlHttp.onload = handler;
		objXmlHttp.onerror = handler;
	}

	//Return the instantiated object
	return objXmlHttp;
}

/*var currentAdElementID;
function writeDart(elementID, sz, pos)
{
	currentAdElementID = elementID;

	if (typeof(sz) == 'undefined')
	{
		return;
	}

	if (typeof(pos) != 'undefined')
	{
		pos = ';pos=' + pos;
	}
	else
	{
		pos = '';
	}

	if (typeof(document.dfp_ord) == 'undefined')
	{
		document.dfp_ord = Math.floor(Math.random() * 999999999);
	}

	if (typeof(document.dfp_tile) == 'undefined')
	{
		document.dfp_tile = 1;
		dfp_dcopt = ';dcopt=ist';
	}
	else
	{
		document.dfp_tile++;
		dfp_dcopt = '';
	}

	xmlHttp = GetXmlHttpObject(writeDartHandler);
	xmlHttp_Get(xmlHttp, http + '//ad.uk.doubleclick.net/adj/' + siteZone + ';kw=' + path.join(',') + ';tile=' + document.dfp_tile + dfp_dcopt + ';true=1;' + kv.replace(/%3D/g, '=').replace(/%3B/g, ';') + ';' + pos + ';sz=' + sz + ';ord=' + document.dfp_ord);
}*/

/*
 * An additional variable, elementID, allows us to target the area to be re-written.
 * The function call now looks like writeDart('horizontalAdSpace', '468x60') or writeDart('verticalAdSpace', '120x600')
 */
function writeDart(elementID, sz, pos)
{
	/*
	 * Instead of document.write()ing a script element, the following line generate an XML string which is parsable by all browsers.
	 * This string needs to contain your completed advert tags within the <div>, which tells the DOMParser how to read it.
	 * I have demonstrated one possible solution below, as it is not possible to include remote scripts in pages for security reasons.
	 * This helps to prevent us from being the target of XSS (Cross Site Scripting) attacks and related cracking activities.
	 *
	 * Obviously, this is just one suggested xmlData string.  There are many ways to implement this part of the code, however the try
	 * {} catch {} block below needs to remain in order for any of this to work in an XML application such as the Saga website.
	 */
	var adID = Math.floor(Math.random() * 999999999);
	var xmlData = '<div xmlns="http://www.w3.org/1999/xhtml"><a class="advertisement" href="http://redirect.doubleclick.net/' + siteZone + ';adID=' + adID + '"><img class="advertisement" src="http://image.doubleclick.net/' + siteZone + ';adID=' + adID + '" alt="Click here for more information!" title="Click here for more information!" /></a></div>';

	// This next block attempts to replace the content of the element referenced in the function call with the parsed string from above.
	try
	{
		var elem = document.getElementById(elementID);
		var children = elem.childNodes;

		for (var i = 0; i < children.length; i++)
		{
			elem.removeChild(children[i]);
		}

		var nodes = new DOMParser().parseFromString(xmlData, 'application/xhtml+xml');
		var range = document.createRange();

		range.selectNodeContents(document.getElementById(elementID));
		range.deleteContents();

		for (var i = 0; i < nodes.childNodes.length; i++)
		{
			document.getElementById(elementID).appendChild(
			nodes.childNodes[i]);
		}
		return true;
	}
	catch (e1)
	{
		// If an error occurs, we attempt the old fashioned method.
		try
		{
			document.getElementById(elementID).innerHTML = xmlData;
			return true;
		}
		catch(e2)
		{
			// If this block is reached, the browser is not capable of rendering adverts.
			return false;
		}
	}
}


function writeDartHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		// Example of what the abortion above retrieves:
		//document.write('<a target="_blank" href="http://ad.uk.doubleclick.net/click;h=v8/3665/0/0/%2a/m;94342960;0-0;0;17181910;1-468/60;22872141/22890024/1;;~aopt=2/1/ff/1;~sscs=%3fhttp://www.saga.co.uk/travel/General3/"><img src="http://m.uk.2mdn.net/viewad/1418124/SagaTravelshopGeneric.gif" border=0 alt="Click here to find out more!"></a>');

		var str = xmlHttp.responseText;
		var xmlData = '<div xmlns="http://www.w3.org/1999/xhtml">' + str.replace('document.write(\'', '').replace(' target="_blank"', '').replace(' border=0', '').replace('\');', '') + '</div>';

		replaceContent(currentAdElementID, xmlData);
	}
}

function ajaxSearchForAddress(house, postcode)
{
	var url = requestURL + "mode=searchForAddress&house=" + escape(house) + "&postcode=" + escape(postcode);

	document.getElementById('loadingAddressDiv').style.display = '';
	xmlHttp = GetXmlHttpObject(ajaxSearchForAddressHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxGetAddress()
{
	if (document.getElementById('moniker'))
	{
		var url = requestURL + "mode=getAddress&moniker=" + escape(document.getElementById('moniker').value);

		document.getElementById('loadingAddressDiv').style.display = '';
		xmlHttp = GetXmlHttpObject(ajaxGetAddressHandler);
		xmlHttp_Get(xmlHttp, url);
	}
	else if (document.getElementById('monikers'))
	{
		var url = requestURL + "mode=getAddress&moniker=" + escape(document.getElementById('monikers').options[document.getElementById('monikers').selectedIndex].value);

		document.getElementById('loadingAddressDiv').style.display = '';
		xmlHttp = GetXmlHttpObject(ajaxGetAddressHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function ajaxGetAddressHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		var str = xmlHttp.responseText;
		var addressArr, addressRegex;
		addressArr = str.split("\n");

		document.getElementById('street').value = addressArr[2];
		document.getElementById('town').value = addressArr[3];
		document.getElementById('county').value = addressArr[4];
		document.getElementById('postcode').value = addressArr[5];
		document.getElementById('loadingAddressDiv').style.display = 'none';
		document.getElementById('manualAddress').style.display = 'none';

		replaceContent('yourAddressDiv', 'Please wait... <img src="themes/default/images/loading.gif" alt="Loading..." />');
		document.getElementById('savedAddress').style.display = '';
		document.getElementById('addressSearch').style.display = 'none';
		document.getElementById('addressCountry').style.display = 'none';
		document.getElementById('searchResults').style.display = 'none';
		ajaxGetFormattedAddress();
	}
}

function ajaxGetFormattedAddress()
{
	if (document.getElementById('moniker'))
	{
		var url = requestURL + "mode=getStandardAddress&moniker=" + escape(document.getElementById('moniker').value);

		xmlHttp = GetXmlHttpObject(ajaxGetFormattedAddressHandler);
		xmlHttp_Get(xmlHttp, url);
	}
	else if (document.getElementById('monikers'))
	{
		var url = requestURL + "mode=getStandardAddress&moniker=" + escape(document.getElementById('monikers').options[document.getElementById('monikers').selectedIndex].value);

		xmlHttp = GetXmlHttpObject(ajaxGetFormattedAddressHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function ajaxGetFormattedAddressHandler()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
	var str = xmlHttp.responseText;

	replaceContent('yourAddressDiv', 'Your address is:<p style="font-size: 0.9em; font-weight: bold; padding: 5px 10px;">' + str.replace(/\n/g, "<br />\n") + '</p>');
	var addressArr = str.split('\n');
	document.getElementById('housenumber').value = addressArr[0];
	if (document.getElementById('housenumber').value.indexOf(document.getElementById('street').value) > 0)
	{
		document.getElementById('housenumber').value = document.getElementById('housenumber').value.replace(document.getElementById('street').value, '');
		document.getElementById('housenumber').value = document.getElementById('housenumber').value.replace(' ', '');
	}
}
}

function showManualEditForm()
{
document.getElementById('addressSearch').style.display = 'none';
document.getElementById('addressCountry').style.display = 'none';
document.getElementById('manualAddress').style.display = '';
	document.getElementById('searchResults').style.display = 'none';
	document.getElementById('savedAddress').style.display = 'none';
}

function showAddressSearchForm()
{
	document.getElementById('addressCountry').style.display = '';
	document.getElementById('countrySearch').selectedIndex = 0;
	document.getElementById('addressSearch').style.display = 'none';
	document.getElementById('manualAddress').style.display = 'none';
	document.getElementById('searchResults').style.display = 'none';
	document.getElementById('savedAddress').style.display = 'none';
}

function ajaxSearchForAddressHandler()
{
	//readyState of 4 or 'complete' represents that data has been returned
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		//Gather the results from the callback
		var str = xmlHttp.responseText;
		if (str.length > 0)
		{
			if (str.substr(0, 7) == 'single:')
			{
				document.getElementById('searchResults').style.display = '';
				//document.getElementById('addressSearch').style.display = 'none';
				replaceContent('searchResultsDiv', str.substr(7));
			}
			else if (str.substr(0, 9) == 'multiple:')
			{
				str = str.substr(9);
				document.getElementById('searchResults').style.display = '';
				replaceContent('searchResultsDiv', '<p class="sectiontext">Please choose from one of the following addresses:<br /><select name="monikers" id="monikers" class="selectfield" style="width: 100%;">' + str + '</select>');
			}
			else
			{
				alert('No addresses found.');
			}
		}

		document.getElementById('loadingAddressDiv').style.display = 'none';
	}
}

function displayCorrectAddressFields(dropdown)
{
	if (dropdown.id == 'country')
	{
		document.getElementById('countrySearch').selectedIndex = dropdown.selectedIndex;
	}
	else
	{
		document.getElementById('country').selectedIndex = dropdown.selectedIndex;
	}

	if (dropdown.options[dropdown.selectedIndex].value == 'United Kingdom')
	{
		document.getElementById('addressSearch').style.display = '';
		document.getElementById('addressCountry').style.display = '';
		document.getElementById('manualAddress').style.display = 'none';
		document.getElementById('searchResults').style.display = 'none';
	}
	else if (dropdown.selectedIndex > 0)
	{
		document.getElementById('manualAddress').style.display = '';
		document.getElementById('addressSearch').style.display = 'none';
		document.getElementById('addressCountry').style.display = 'none';
		document.getElementById('searchResults').style.display = 'none';
	}
	else
	{
		document.getElementById('addressSearch').style.display = 'none';
		document.getElementById('manualAddress').style.display = 'none';
		document.getElementById('addressCountry').style.display = '';
		document.getElementById('searchResults').style.display = 'none';
	}
}

function validateName(field, errorEmpty, popupError)
{
	if (isEmpty(field.value) || containsWeirdChars(field.value))
	{
		if (errorEmpty)
		{
			field.className = 'textfielderror';
		}
		else
		{
			field.className = 'textfieldinvalid';
		}

		if (popupError)
		{
			alert('The name you have entered is invalid.  Please correct it before continuing.');
		}
		return false;
	}
	else
	{
		field.className = 'textfieldvalid';
		return true;
	}
}

function validateHouse(field, errorEmpty, popupError)
{
	if (isEmpty(field.value))// || containsWeirdChars(field.value))
	{
		if (errorEmpty)
		{
			field.className = 'textfielderror';
		}
		else
		{
			field.className = 'textfieldinvalid';
		}

		if (popupError)
		{
			alert('The house you have entered is invalid.  Please correct it before continuing.');
		}
		return false;
	}
	else
	{
		field.className = 'textfieldvalid';
		return true;
	}
}

function validatePostcode(field, country, errorEmpty, popupError)
{
	if (country)
	{
		if (!isPostcode(field.value, country.options[country.selectedIndex].value))
		{
			if (errorEmpty)
			{
				field.className = 'textfielderror';
			}
			else
			{
				field.className = 'textfieldinvalid';
			}

			if (popupError)
			{
				alert('The post- or zipcode you have entered is invalid.  Please correct it before continuing.');
			}
			return false;
		}
		else
		{
			field.className = 'textfieldvalid';
			return true;
		}
	}
	else
	{
		if (!isPostcode(field.value, 'United Kingdom'))
		{
			if (errorEmpty)
			{
				field.className = 'textfielderror';
			}
			else
			{
				field.className = 'textfieldinvalid';
			}

			if (popupError)
			{
				alert('The post- or zipcode you have entered is invalid.  Please correct it before continuing.');
			}
			return false;
		}
		else
		{
			field.className = 'textfieldvalid';
			return true;
		}
	}
}

var usernameFieldID;
var displayNameFieldID;
function validateUsername(field, errorEmpty, popupError, useAJAX)
{
	if (!isUsername(field.value))
	{
		if (isEmpty(field.value))
		{
			if (errorEmpty)
			{
				field.className = 'textfielderror';
			}
			else
			{
				field.className = 'textfieldinvalid';
			}
		}
		else
		{
			field.className = 'textfielderror';
		}

		if (popupError)
		{
			alert('The username you have selected contains invalid characters.  Please correct it and try again.  Usernames may only contain letters, numbers, underscores and hyphens.');
		}
		return false;
	}
	else
	{
		if (useAJAX)
		{
			ajaxCheckUsername(field);
		}
		else
		{
			field.className = 'textfieldvalid';
		}
		return true;
	}
}

function validateDisplayName(field, errorEmpty, popupError, useAJAX)
{
	if (!isDisplayName(field.value))
	{
		if (isEmpty(field.value))
		{
			if (errorEmpty)
			{
				field.className = 'textfielderror';
			}
			else
			{
				field.className = 'textfieldinvalid';
			}
		}
		else
		{
			field.className = 'textfielderror';
		}

		if (popupError)
		{
			alert('The display name you have selected contains invalid characters.  Please correct it and try again.  Display names may not contain any non-alphanumeric characters, such as currency symbols or punctuation.  They may contain underscores and hyphens..');
		}
		return false;
	}
	else
	{
		if (useAJAX)
		{
			ajaxCheckDisplayName(field);
		}
		else
		{
			field.className = 'textfieldvalid';
		}
		return true;
	}
}

function ajaxCheckUsername(field)
{
	usernameFieldID = field.id;
	var url = requestURL + 'mode=checkUsername&username=' + escape(field.value);

	xmlHttp = GetXmlHttpObject(ajaxCheckUsernameHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxCheckUsernameHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		var str = xmlHttp.responseText;
		if (str == 'available')
		{
			document.getElementById(usernameFieldID).className = 'textfieldvalid';
			replaceContent('usernameBorked', '<div xmlns="http://www.w3.org/1999/xhtml">&#xa0;</div>');
		}
		else
		{
			document.getElementById(usernameFieldID).className = 'textfielderror';
			replaceContent('usernameBorked', '<div xmlns="http://www.w3.org/1999/xhtml" class="errorbox">The username you have selected is already in use.  Please choose another one and try again.</div>');
		}
	}
}

function getWindowWidthHeight() {
        if (self.innerWidth) {
                windowWidth = self.innerWidth;
                windowHeight = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientWidth) {
                windowWidth = document.documentElement.clientWidth;
                windowHeight = document.documentElement.clientHeight;
        }
        else if (document.body) {
                windowWidth = document.body.clientWidth;
                windowHeight = document.body.clientHeight;
        }
        else {
                windowWidth = 0;
                windowHeight = 0;
        };

        return;
}

function ajaxCheckDisplayName(field)
{
	displayNameFieldID = field.id;
	var url = requestURL + 'mode=checkDisplayName&displayName=' + escape(field.value);

	xmlHttp = GetXmlHttpObject(ajaxCheckDisplayNameHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxCheckDisplayNameHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		var str = xmlHttp.responseText;
		if (str == 'available')
		{
			document.getElementById(displayNameFieldID).className = 'textfieldvalid';
			replaceContent('displayNameBorked', '<div xmlns="http://www.w3.org/1999/xhtml">&#xa0;</div>');
		}
		else
		{
			document.getElementById(displayNameFieldID).className = 'textfielderror';
			replaceContent('displayNameBorked', '<div xmlns="http://www.w3.org/1999/xhtml" class="errorbox">The display name you have selected is already in use.  Please choose another one and try again.</div>');
		}
	}
}

function validateDate(field, errorEmpty, popupError)
{
	if (!isDate(field.value))
	{
		if (errorEmpty)
		{
			field.className = 'textfielderror';
		}
		else
		{
			field.className = 'textfieldinvalid';
		}

		if (popupError)
		{
			alert('The date you have entered is invalid.  Please correct it before continuing.');
		}
		return false;
	}
	else
	{
		field.className = 'textfieldvalid';
		return true;
	}
}

function validateMaritalStatus(field, star)
{
	if (field.value == '')
	{
		field.className = 'selectfielderror';
		star.style.display = '';
		return false;
	}
	else
	{
		field.className = 'selectfieldvalid';
		star.style.display = 'none';
		return true;
	}
}

function validateGender(field, star)
{
	if (field.value == '')
	{
		field.className = 'selectfielderror';
		star.style.display = '';
		return false;
	}
	else
	{
		field.className = 'selectfieldvalid';
		star.style.display = 'none';
		return true;
	}
}

function checkCompleteRegistrationForm(form, errorEmpty, popupErrors)
{
	var errored = false;
	if (!validateName(form.firstname, true, false))
	{
		errored = true;
	}

	if (!validateName(form.surname, true, false))
	{
		errored = true;
	}

	if (!validateDate(form.dob, true, false))
	{
		errored = true;
	}

	if (!validateGender(form.gender, document.getElementById('genderasterisk')))
	{
		errored = true;
	}

	if (!validateMaritalStatus(form.maritalstatus, document.getElementById('maritalstatusasterisk')))
	{
		errored = true;
	}

	if (!validatePostcode(form.postcode, form.country, true, false))
	{
		errored = true;
	}

	if (!validateHouse(form.house, true, false))
	{
		errored = true;
	}

	if (errored)
	{
		if (document.getElementById('manualAddress').style.display == 'none' && !validatePostcode(form.postcode, form.country, true, false))
		{
			alert('Please enter your address before continuing.');
		}
		else
		{
			alert('Please correct all invalid information before continuing.  Fields containing invalid information are displayed in red and will turn green once they contain valid information.');
		}
		return false;
	}
	else
	{
		return true;
	}
}

function isNumeric(str)
{
	if (!str.match(/^([0-9]+)$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function isDate(str)
{
	if (!str.match(/^([0-3][0-9])([\/\-\.])([0-1][0-9])([\/\-\.])([1-2][0-9]{3})$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function containsWeirdChars(str)
{
	if (str.match(/([\!\"£\$%\^\&\*\(\)_\+=|\\\/<>,\.@#~;\:¬`¦€\n\t\r])/))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isName(str)
{
	if (!str.match(/^([A-Za-z\-\'\ ]+)$/) || str.length <= 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function isDisplayName(str)
{
	if (!str.match(/^([0-9A-Za-z\-\'\ _\.]+)$/) || str.length <= 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function isUsername(str)
{
	if (!str.match(/^([0-9A-Za-z\-_\.]+)$/) || str.length <= 0)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function isPostcode(postcode, country)
{
	if (postcode.length <= 0)
	{
		return false;
	}
	else if (country == 'United Kingdom')
	{
		if (postcode.match(/^((([A-PR-UWYZ])([0-9][0-9A-HJKS-UW]?))|(([A-PR-UWYZ][A-HK-Y])([0-9][0-9ABEHMNPRV-Y]?))\s{0,2}(([0-9])([ABD-HJLNP-UW-Z])([ABD-HJLNP-UW-Z])))|(((GI)(R))\s{0,2}((0)(A)(A)))$/i))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (country == 'United States of America')
	{
		if (postcode.replace(/[^0-9\ \-]/, '').match(/^[0-9]{5}(\-[0-9]{4})?$/))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else if (country == 'Canada')
	{
		if (postcode.replace(/[^A-Za-z0-9]/g, '').match(/^([A-Za-z][0-9][A-Za-z][0-9][A-Za-z][0-9])$/))
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return true;
	}
}

function isGoodURL(str)
{
	//if (!str.match(/(http(s?):\/\/)[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2,5}\?[A-Za-z0-9&]
	//([\w]+:\w+@)?
	//([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))
	//(:[\d]{1,5})?
	//((/?\w+/)+|/?)
	//(\w+\.[\w]{3,4})?
	//((\?\w+=\w+)?(&\w+=\w+)*)?
	//$/))
	//if (!str.match(/^http(s?):\/\/[A-Za-z0-9\.-]{4,}*/))
	//if (!str.match(/^http(s?):\/\/([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+\.[^#?\s]+)(#[\w\-]+)?$/))
	//if (!str.match(/^http(s?):\/\/([^:\/\s]+)([A-Za-z0-9\.\-\?\/]+)$/))
	//if (!str.match(/^(http(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?/))
	//{
	//	return false;
	//}
	//else
	//{
		return true;
	//}
}

function isEmail(str)
{
	if (!str.match(/^(([a-zA-Z0-9]{1}[a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/))
	{
		return false;
	}
	else
	{
		return true;
	}
}

function isEmpty(str)
{
	if (str.length <= 0 || str == '' || str == null)
	{
		return true;
	}
	else
	{
		return false;
	}
}



function validatePassword(password, username, errorEmpty, popupErrors)
{
	if (!isEmpty(password.value.length))
	{
/*		if (password.value.indexOf(username.value))
		{
			password.className = 'textfielderror';
			if (popupErrors)
			{
				alert('Your password cannot contain your username.  Please choose another password.');
			}
			return false;
		}
		else if (password.length < 6)
		{
			password.className = 'textfielderror';
			if (popupErrors)
			{*/
		if (password.value.length < 6)
		{
			if (popupErrors)
			{
				alert('Your password must be at least 6 characters in length.');
			}
			password.className = 'textfielderror';
			return false;
		}
		password.className = 'textfield';
		return true;
	}
	else
	{
		password.className = 'textfielderror';
		return false;
	}
}

function checkRegistrationForm(form, errorEmpty, popupErrors)
{
	var errored = false;

	if (!validateUsername(form.username, errorEmpty, true, false))
	{
		errored = true;
	}

	if (!validateDisplayName(form.displayname, errorEmpty, true, false))
	{
		errored = true;
	}

	if (!form.tos.checked || !form.privacypolicy.checked)
	{
		alert('You must tick both of the boxes at the bottom of this page before you can register.');
		errored = true;
	}

/*	if (!validatePassword(form.drowssap, form.username, errorEmpty, true))
	{
		errored = true;
	}

	if (form.drowssap.value != form.drowssapconfirm.value)
	{
		form.drowssapconfirm.className = 'textfielderror';
		errored = true;
	}
	else
	{
		form.drowssapconfirm.className = 'textfield';
	}

	if (form.confirmemail.value != form.email.value)
	{
		form.confirmemail.className = 'textfielderror';
		errored = true;
	}
	else
	{
		form.confirmemail.className = 'textfield';
	}*/

/*	if (!validateEmail('email', errorEmptyFields))
	{
		document.getElementById('emailasterisk').style.display = '';
		errored = true;
	}
	else
	{
		document.getElementById('emailasterisk').style.display = 'none';
	}

	if (!validateEmail('confirmemail', errorEmptyFields))
	{
		errored = true;
		document.getElementById('emailasterisk').style.display = '';
	}
	else
	{
		document.getElementById('emailasterisk').style.display = 'none';
	}

	if (!validatePassword('drowssap', 'username', errorEmptyFields))
	{
		errored = true;

		if (popupPasswordError)
		{
			alert('#{errorPasswordNotStrongEnough}');
		}
		document.getElementById('drowssapasterisk').style.display = '';
	}
	else
	{
		document.getElementById('drowssapasterisk').style.display = 'none';
	}

	if (!compareFields('email', 'confirmemail', errorEmptyFields))
	{
		errored = true;

		if (popupEmailError)
		{
			alert('#{errorEmailAddressesDoNotMatch}');
		}
		document.getElementById('emailasterisk').style.display = '';
	}
	else
	{
		document.getElementById('emailasterisk').style.display = 'none';
	}

	if (!compareFields('drowssap', 'drowssapconfirm', errorEmptyFields))
	{
		errored = true;

		if (popupPasswordError)
		{
			alert('#{errorPasswordsDoNotMatch}');
		}
		document.getElementById('drowssapasterisk').style.display = '';
	}
	else
	{
		document.getElementById('drowssapasterisk').style.display = 'none';
	}

	if (!document.getElementById('tos').checked)
	{
		errored = true;
		document.getElementById('tosasterisk').style.display = '';
	}

	if (!document.getElementById('privacypolicy').checked)
	{
		errored = true;
		document.getElementById('privacypolicyasterisk').style.display = '';
	}*/

	if (!errored)
	{
		return true;
	}
	else
	{
		if (errorEmpty && popupErrors)
		{
			alert('Some of the information you have entered is invalid.  Please check the information you have entered into this form before trying to submit it again.  Invalid information will be highlighted in red and will turn green once it is acceptable.');
		}
		return false;
	}
}

function startList()
{
	if (document.all && document.getElementById)
	{
		navRoot = document.getElementById("navList");
		for (i = 0; i < navRoot.childNodes.length; i++)
		{
			node = navRoot.childNodes[i];
			if (node.nodeName == "LI")
			{
				node.onmouseover = function()
				{
					this.className = "navItemOver";
				}

				node.onmouseout = function()
				{
					this.className = "navItem";
				}
			}
		}
	}
}

function showAddCommentPane(entryID)
{
	if (document.getElementById('addcommentpane-' + entryID).style.display == 'none')
	{
		document.getElementById('addcommentpane-' + entryID).style.display = '';
	}
	else
	{
		document.getElementById('addcommentpane-' + entryID).style.display = 'none';
	}
}

function ajaxSaveProfile(profileText, userID)
{
	var url = requestURL + 'mode=saveProfile&profileText=' + escape(profileText.value) + '&userID=' + escape(userID);

	document.getElementById('savingProfile').style.display = '';
	xmlHttp = GetXmlHttpObject(ajaxSaveProfileHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxSaveProfileHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		replaceContent('currentProfileText', xmlHttp.responseText);
		document.getElementById('currentProfileText').style.display = '';
		document.getElementById('editProfileFormSurround').style.display = 'none';
		document.getElementById('savingProfile').style.display = 'none';
	}
}

var currentInterestID;
function ajaxSaveInterest(interestID, interestText, userID)
{
	var url = requestURL + 'mode=saveInterest&interestID=' + escape(interestID) + '&interestValue=' + escape(interestText.value) + '&userID=' + escape(userID);
	currentInterestID = interestID;

	document.getElementById('savingInterest_' + interestID).style.display = '';
	xmlHttp = GetXmlHttpObject(ajaxSaveInterestHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxSaveInterestHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		replaceContent('currentInterestText_' + currentInterestID, xmlHttp.responseText);
		document.getElementById('currentInterestText_' + currentInterestID).style.display = '';
		document.getElementById('editInterestFormSurround_' + currentInterestID).style.display = 'none';
		document.getElementById('savingInterest_' + currentInterestID).style.display = 'none';
	}
}

function deleteInterest(interestID, userID)
{
	var response = confirm('Are you sure you want to remove this interest from your profile?');

	if (response)
	{
		var url = requestURL + 'mode=deleteInterest&interestID=' + escape(interestID) + '&userID=' + escape(userID);
		currentInterestID = interestID;

		document.getElementById('deletingInterest_' + interestID).style.display = '';
		xmlHttp = GetXmlHttpObject(ajaxDeleteInterestHandler);
		xmlHttp_Get(xmlHttp, url);
	}
	else
	{
		alert('The interest has not been removed.');
	}
}

function ajaxDeleteInterestHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		if (xmlHttp.responseText == '')
		{
			if (document.getElementById('newInterestID'))
			{
				replaceContent('interestListSurround', '<select xmlns="http://www.w3.org/1999/xhtml" id="newInterestID" class="selectField" name="newInterestID">' + document.getElementById('newInterestID').innerHTML + '<option value="' + currentInterestID + '">' + document.getElementById('interestName_' + currentInterestID).innerHTML + '</option></select>');
			}

			document.getElementById('interestRow_' + currentInterestID).style.display = 'none';
			document.getElementById('deletingInterest_' + currentInterestID).style.display = 'none';
		}
		else
		{
			alert('Permission denied');
			document.getElementById('deletingInterest_' + currentInterestID).style.display = 'none';
		}
	}
}

function ajaxAddInterest(interestID, interestText, userID)
{
	var url = requestURL + 'mode=addInterest&interestID=' + escape(interestID) + '&interestValue=' + escape(interestText.value) + '&userID=' + escape(userID);

	document.getElementById('addingInterest').style.display = '';
	xmlHttp = GetXmlHttpObject(ajaxAddInterestHandler);
	xmlHttp_Get(xmlHttp, url);
}

function ajaxAddInterestHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		replaceContent('interestSectionBody', xmlHttp.responseText);
	}
}

var currentEntryID;
function validateBlogComment(entryID)
{
	currentEntryID = entryID;
	document.getElementById('commentmessage-' + entryID).style.display = '';

	if (document.getElementById('commentbody-' + entryID).value == '' || document.getElementById('commentsubject-' + entryID).value == '')
	{
		replaceContent('commentmessage-' + entryID, '<div xmlns="http://www.w3.org/1999/xhtml"><strong>You must enter both a comment and a subject.</strong></div>');
	}
	else
	{
		document.getElementById('commentmessage-' + entryID).style.display = 'none';
		document.getElementById('commentprocessing-' + entryID).style.display = '';
		document.getElementById('commentsubjecttext-' + entryID).style.display = 'none';
		document.getElementById('commentsubject-' + entryID).style.display = 'none';
		document.getElementById('commentbodytext-' + entryID).style.display = 'none';
		document.getElementById('commentbody-' + entryID).style.display = 'none';
		document.getElementById('postcommentbutton-' + entryID).disabled = true;
		document.getElementById('postcommentbutton-' + entryID).style.display = 'none';

		var subject = document.getElementById('commentsubject-' + entryID).value;
		var body = document.getElementById('commentbody-' + entryID).value.replace(/\n/g, '[||]');
		var url = requestURL + 'mode=postblogcomment&entryid=' + entryID + '&subject=' + escape(subject) + '&body=' + escape(body);

		xmlHttp = GetXmlHttpObject(ajaxPostBlogCommentHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function ajaxPostBlogCommentHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		document.getElementById('commentprocessing-' + currentEntryID).style.display = 'none';
		document.getElementById('commentsubject-' + currentEntryID).style.display = '';
		document.getElementById('commentsubjecttext-' + currentEntryID).style.display = '';
		document.getElementById('commentbody-' + currentEntryID).style.display = '';
		document.getElementById('commentbodytext-' + currentEntryID).style.display = '';
		document.getElementById('postcommentbutton-' + currentEntryID).disabled = false;
		document.getElementById('postcommentbutton-' + currentEntryID).style.display = '';

		if (xmlHttp.responseText == 'error')
		{
			replaceContent('commentmessage-' + currentEntryID, '<div xmlns="http://www.w3.org/1999/xhtml">An error occured whilst processing the comment.</div>');
		}
		else
		{
			document.getElementById('commentform-' + currentEntryID).reset();
			replaceContent('commentmessage-' + currentEntryID, '<div xmlns="http://www.w3.org/1999/xhtml"></div>');
			document.getElementById('addcommentpane-' + currentEntryID).style.display = 'none';
			//alert('<div xmlns="http://www.w3.org/1999/xhtml">' + xmlHttp.responseText + document.getElementById('blogentrycomments').innerHTML + '</div>');
			replaceContent('blogentrycomments', '<div xmlns="http://www.w3.org/1999/xhtml">' + xmlHttp.responseText + document.getElementById('blogentrycomments').innerHTML + '</div>');
		}
	}
}

function showReplyToCommentPane(commentID)
{
	if (document.getElementById('showcommentreplypane-' + commentID).style.display == 'none')
	{
		document.getElementById('showcommentreplypane-' + commentID).style.display = '';
	}
	else
	{
		document.getElementById('showcommentreplypane-' + commentID).style.display = 'none'
	}
}

var currentParentID;
function validateReplyToBlogComment(entryID, parentID)
{
	currentParentID = parentID;

	if (document.getElementById('commentreplybody-' + parentID).value == '' || document.getElementById('commentreplysubject-' + parentID).value == '')
	{
		replaceContent('commentreplymessage-' + parentID, '<strong>You must enter both a comment and a subject.</strong>');
	}
	else
	{
		document.getElementById('commentreplymessage-' + parentID).style.display = 'none';
		document.getElementById('commentreplyprocessing-' + parentID).style.display = '';
		document.getElementById('commentreplysubjecttext-' + parentID).style.display = 'none';
		document.getElementById('commentreplysubject-' + parentID).style.display = 'none';
		document.getElementById('commentreplybodytext-' + parentID).style.display = 'none';
		document.getElementById('commentreplybody-' + parentID).style.display = 'none';
		document.getElementById('postcommentreplybutton-' + parentID).disabled = true;
		document.getElementById('postcommentreplybutton-' + parentID).style.display = 'none';

		var subject = document.getElementById('commentreplysubject-' + parentID).value;
		var body = document.getElementById('commentreplybody-' + parentID).value.replace(/\n/g, '[||]');
		var level = document.getElementById('commentreplylevel-' + parentID).value;
		var url = requestURL + 'mode=replytoblogcomment&entryid=' + entryID + '&parentid=' + parentID + '&subject=' + subject + '&body=' + body + '&currentlevel=' + level;
		xmlHttp = GetXmlHttpObject(ajaxReplyToBlogCommentHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function ajaxReplyToBlogCommentHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		document.getElementById('commentreplyprocessing-' + currentParentID).style.display = 'none';
		document.getElementById('commentreplysubject-' + currentParentID).style.display = '';
		document.getElementById('commentreplysubjecttext-' + currentParentID).style.display = '';
		document.getElementById('commentreplybody-' + currentParentID).style.display = '';
		document.getElementById('commentreplybodytext-' + currentParentID).style.display = '';
		document.getElementById('postcommentreplybutton-' + currentParentID).disabled = false;
		document.getElementById('postcommentreplybutton-' + currentParentID).style.display = '';

		if (xmlHttp.responseText == 'error')
		{
			replaceContent('commentreplymessage-' + currentParentID, 'An error occured whilst processing the comment.');
		}
		else
		{
			document.getElementById('commentreplyform-' + currentParentID).reset();
			replaceContent('commentreplymessage-' + currentParentID, '<div xmlns="http://www.w3.org/1999/xhtml"></div>');
			document.getElementById('showcommentreplypane-' + currentParentID).style.display = 'none';
			document.getElementById('replytoblogcommentreply-' + currentParentID).style.display = '';
			replaceContent('replytoblogcommentreply-' + currentParentID, '<div xmlns="http://www.w3.org/1999/xhtml">' + xmlHttp.responseText + document.getElementById('replytoblogcommentreply-' + currentParentID).innerHTML + '</div>');
			// alert(xmlHttp.responseText);
			// replaceContent('replytoblogcommentreply-' + currentParentID, "<div><textarea id=\"test\">"+xmlHttp.responseText + "<\/textarea><\/div>");
		}
	}
}

function showHideBodyLink(commentID)
{
	if (document.getElementById('commentshowhidebody-' + commentID).style.display == 'none')
	{
		document.getElementById('blogcommentshowbodylink-' + commentID).style.display = 'none';
		document.getElementById('blogcommenthidebodylink-' + commentID).style.display = '';
		document.getElementById('commentshowhidebody-' + commentID).style.display = '';
	}
	else
	{
		document.getElementById('blogcommentshowbodylink-' + commentID).style.display = '';
		document.getElementById('blogcommenthidebodylink-' + commentID).style.display = 'none';
		document.getElementById('commentshowhidebody-' + commentID).style.display = 'none';
	}
}

function postBlogComment(entryID)
{
	if (document.getElementById('commentsubject-' + entryID).value == '' || document.getElementById('commentbody-' + entryID).value == '')
	{
		replaceContent('commentmessage-' + entryID, '<div xmlns="http://www.w3.org/1999/xhtml"><strong>You must enter both a comment and a subject.</strong></div>');
		return false;
	}
	else
	{
		replaceContent('commentmessage-' + entryID, '<div xmlns="http://www.w3.org/1999/xhtml"></div>');
		return true;
	}
}

var currentCommentID;
function deleteBlogComment(commentID)
{
	if (confirm('Are you sure you wish to delete the selected comment? This cannot be undone.') == true)
	{
		document.getElementById('commentshowhidebody-' + commentID).style.display = 'none';
		replaceContent('commentprocessing-' + commentID, '<div xmlns="http://www.w3.org/1999/xhtml"><img src="' + siteURL + 'themes/default/images/loading.gif" alt="Loading..." /></div>');
		document.getElementById('commentprocessing-' + commentID).style.textAlign = 'center';

		var url = requestURL + 'mode=deleteblogcomment&commentid=' + commentID;
		currentCommentID = commentID;

		xmlHttp = GetXmlHttpObject(deleteBlogCommentHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function deleteBlogCommentHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		if (xmlHttp.responseText == 'success')
		{
			document.getElementById('commentprocessing-' + currentCommentID).style.display = 'none';

			document.getElementById('commentshowhidebody-' + currentCommentID).style.display = '';
			document.getElementById('commentshowhidebody-' + currentCommentID).style.backgroundColor = '#A84A40';
			replaceContent('commentshowhidebody-' + currentCommentID, '<div xmlns="http://www.w3.org/1999/xhtml">The comment was successfully deleted.<\/div>');
			document.getElementById('commentshowhidebody-' + currentCommentID).style.padding = '5px';
			document.getElementById('commentshowhidebody-' + currentCommentID).style.color = '#fff';
			document.getElementById('commentshowhidebody-' + currentCommentID).style.textAlign = 'justify';

			document.getElementById('blogcommentheader-' + currentCommentID).style.display = 'none';
			document.getElementById('commentsurround-' + currentCommentID).className = 'blogcommentsurround';

			document.getElementById('actionbutton-' + currentCommentID).style.display = 'none';
			document.getElementById('actionbutton-' + currentCommentID).disabled = true;
		}
	}
}

function reinstateBlogComment(commentID)
{
	if (confirm('Are you sure you wish to reinstate the selected comment?') == true)
	{
		document.getElementById('commentshowhidebody-' + commentID).style.display = 'none';
		replaceContent('commentprocessing-' + commentID, '<div xmlns="http://www.w3.org/1999/xhtml"><img src="' + siteURL + 'themes/default/images/loading.gif" alt="Loading..." /></div>');
		document.getElementById('commentprocessing-' + commentID).style.textAlign = 'center';

		var url = requestURL + 'mode=reinstateblogcomment&commentid=' + commentID;
		currentCommentID = commentID;

		xmlHttp = GetXmlHttpObject(reinstateBlogCommentHandler);
		xmlHttp_Get(xmlHttp, url);
	}
}

function reinstateBlogCommentHandler()
{
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
	{
		if (xmlHttp.responseText == 'success')
		{
			document.getElementById('commentprocessing-' + currentCommentID).style.display = 'none';
			document.getElementById('commentshowhidebody-' + currentCommentID).style.display = '';
			document.getElementById('commentsurround-' + currentCommentID).className = 'blogcommentsurroundnew';
			document.getElementById('blogcommentheader-' + currentCommentID).className = 'blogcommentheader';
			document.getElementById('blogcommentfooter-' + currentCommentID).className = 'blogcommentfooter';
			document.getElementById('actionbutton-' + currentCommentID).className = 'blogdeletebutton';
			document.getElementById('actionbutton-' + currentCommentID).onclick = function()
			{
				eval('deleteBlogComment(' + currentCommentID + ');');
			};
		}
	}
}

var commentErrorBoxVisible = false;
var visibilityErrorBoxVisible = false;
var subjectErrorBoxVisible = false;
var allowCommentsErrored = false;
var visibilityErrored = false;
var subjectErrored = false;
function validateEditBlogEntryForm()
{
	if (document.getElementById('allowcomments').value == '')
	{
		if (!commentErrorBoxVisible)
		{
			var commentErrorBox = document.createElement('div');
			commentErrorBox.setAttribute('className', 'errorbox');
			commentErrorBox.setAttribute('class', 'errorbox');
			commentErrorBox.setAttribute('id', 'commentserrorbox');
			commentErrorBox.innerHTML = 'You must make a selection from the \'Allow comments from:\' drop-down box. Please do so and try again.';

			document.getElementById('editblogentryform').parentNode.insertBefore(commentErrorBox, document.getElementById('editblogentryform'));
			allowCommentsErrored = true;
			commentErrorBoxVisible = true;
		}
	}
	else
	{
		if (commentErrorBoxVisible)
		{
			document.getElementById('commentserrorbox').style.display = 'none';
		}

		allowCommentsErrored = false;
	}

	if (document.getElementById('visibility').value == '')
	{
		if (!visibilityErrorBoxVisible)
		{
			var visibilityErrorBox = document.createElement('div');
			visibilityErrorBox.setAttribute('className', 'errorbox');
			visibilityErrorBox.setAttribute('class', 'errorbox');
			visibilityErrorBox.setAttribute('id', 'visibilityerrorbox');
			visibilityErrorBox.innerHTML = 'You must make a selection from the \'Visibility\' drop-down box. Please do so and  try again.';


			document.getElementById('editblogentryform').parentNode.insertBefore(visibilityErrorBox, document.getElementById('editblogentryform'));
			visibilityErrored = true;
			visibilityErrorBoxVisible = true;
		}
	}
	else
	{
		if (visibilityErrorBoxVisible)
		{
			document.getElementById('visibilityerrorbox').style.display = 'none';
		}

		visibilityErrored = false;
	}

	if (document.getElementById('subject').value == '')
	{
		if (!subjectErrorBoxVisible)
		{
			var subjectErrorBox = document.createElement('div');
			subjectErrorBox.setAttribute('className', 'errorbox');
			subjectErrorBox.setAttribute('class', 'errorbox');
			subjectErrorBox.setAttribute('id', 'subjecterrorbox');
			subjectErrorBox.innerHTML = 'You must enter a subject for your blog entry. Please do so and try again.';

			document.getElementById('editblogentryform').parentNode.insertBefore(subjectErrorBox, document.getElementById('editblogentryform'));

			subjectErrored = true;
			subjectErrorBoxVisible = true;
			formErrored = true;
		}
	}
	else
	{
		if (subjectErrorBoxVisible)
		{
			document.getElementById('subjecterrorbox').style.display = 'none';
		}

		subjectErrored = false;
	}

	if (allowCommentsErrored || visibilityErrored || subjectErrored)
	{
		return false;
	}
	else
	{
		return true;
	}
}

function editBlogEntry(entryID)
{
	window.location = siteURL + 'blogs/edit/' + entryID + '/';
}

function deleteBlogEntry(entryID)
{
	var response = confirm('Are you sure you want to delete this entry?');
	if (response)
	{
		window.location = siteURL + 'blogs/delete/' + entryID + '/';
	}
	else
	{
		alert('Deletion cancelled.');
	}
}

function toggleBlogCommentVisibility(commentID)
{
	if (document.getElementById('commentshowhidebody-' + commentID).style.display == 'none')
	{
		document.getElementById('commentshowhidebody-' + commentID).style.display = '';
	}
	else
	{
		document.getElementById('commentshowhidebody-' + commentID).style.display = 'none';
	}
}

function showHelp(key)
{
	if (mouseOverHelpEntries[key] != null)
	{
		document.getElementById('mouseoverhelp').innerHTML = mouseOverHelpEntries[key];
		document.getElementById('mouseoverhelptwo').innerHTML = mouseOverHelpEntries[key];
	}
	else
	{
		document.getElementById('mouseoverhelp').innerHTML = "#{errorCouldNotDisplayMouseOverHelpEntryText}";
		document.getElementById('mouseoverhelptwo').innerHTML = "#{errorCouldNotDisplayMouseOverHelpEntryText}";
	}
}

function validateEmail(fieldName, errorEmptyFields)
{
	if (!isEmail(document.getElementById(fieldName).value))
	{
		if (isEmpty(document.getElementById(fieldName).value))
		{
			if (errorEmptyFields)
			{
				document.getElementById(fieldName).className = 'textfielderror';
			}
			else
			{
				document.getElementById(fieldName).className = 'textfieldinvalid';
			}
		}
		else
		{
			document.getElementById(fieldName).className = 'textfielderror';
		}
		return false;
	}
	else
	{
		document.getElementById(fieldName).className = 'textfieldvalid';
		return true;
	}
}

function compareFields(fieldOne, fieldTwo, errorEmptyFields)
{
	if (document.getElementById(fieldOne).value != document.getElementById(fieldTwo).value || isEmpty(document.getElementById(fieldOne).value))
	{
		if (isEmpty(document.getElementById(fieldOne).value))
		{
			if (errorEmptyFields)
			{
				document.getElementById(fieldOne).className = 'textfielderror';
			}
			else
			{
				document.getElementById(fieldOne).className = 'textfieldinvalid';
			}
		}
		else
		{
			document.getElementById(fieldOne).className = 'textfielderror';
		}

		if (isEmpty(document.getElementById(fieldTwo).value))
		{
			if (errorEmptyFields)
			{
				document.getElementById(fieldTwo).className = 'textfielderror';
			}
			else
			{
				document.getElementById(fieldTwo).className = 'textfieldinvalid';
			}
		}
		else
		{
			document.getElementById(fieldTwo).className = 'textfielderror';
		}
		return false;
	}
	else
	{
		document.getElementById(fieldOne).className = 'textfieldvalid';
		document.getElementById(fieldTwo).className = 'textfieldvalid';
		return true;
	}
}

function checkEditProfileForm(errorEmptyFields, popupPasswordError, popupEmailError)
{
	var errored = false;
	if (!validateHouse(document.getElementById('editprofileform').house, errorEmptyFields, false))
	{
		errored = true;
	}

	if (!validatePostcode(document.getElementById('postcode'), document.getElementById('country'), errorEmptyFields, popupEmailError))
	{
		errored = true;
	}

	if (!compareFields('emailaddress', 'emailaddressconfirm', errorEmptyFields))
	{
		errored = true;

		if (popupEmailError)
		{
			alert('#{errorEmailAddressesDoNotMatch}');
		}
	}

	if (!validateEmail('emailaddress', errorEmptyFields))
	{
		errored = true;
	}

	if (!validateEmail('emailaddressconfirm', errorEmptyFields))
	{
		errored = true;
	}

	if (!validatePassword(document.getElementById('drowssap'), document.getElementById('username'), errorEmptyFields, popupPasswordError))
	{
		errored = true;
	}

	if (!compareFields('drowssap', 'drowssapconfirm', errorEmptyFields))
	{
		errored = true;

		if (popupPasswordError)
		{
			alert('#{errorPasswordsDoNotMatch}');
		}
	}


	if (!errored)
	{
		return true;
	}

	else
	{
		if (popupPasswordError || popupEmailError)
		{
			alert('#{errorCheckProfileFormValues}');
		}
		return false;
	}
}

function showEditProfileForm()
{
	document.getElementById('currentProfileText').style.display = 'none';
	document.getElementById('editProfileFormSurround').style.display = '';
}

function hideEditProfileForm()
{
	document.getElementById('currentProfileText').style.display = '';
	document.getElementById('editProfileFormSurround').style.display = 'none';
}

function showEditInterestForm(interest)
{
	document.getElementById('currentInterestText_' + interest).style.display = 'none';
	document.getElementById('editInterestFormSurround_' + interest).style.display = '';
}

function hideEditInterestForm(interest)
{
	document.getElementById('currentInterestText_' + interest).style.display = '';
	document.getElementById('editInterestFormSurround_' + interest).style.display = 'none';
}

function updateAvatarPreview(fieldID, userID, imageID)
{
	if (imageID == 15893 || imageID == 5894 || imageID == 15895 || imageID == 15896 || imageID == 15897 || imageID == 15898 || imageID == 15899 || imageID == 15900 || imageID == 15901 || imageID == 15902 || imageID == 15903 || imageID == 15904 || imageID == 15905 || imageID == 15907 || imageID == 15908 || imageID == 15909 || imageID == 15910 || imageID == 15911 || imageID == 15912 || imageID == 15913 || imageID == 15915 || imageID == 15917 || imageID == 15918 || imageID == 15919 || imageID == 15920)
	{
		document.getElementById(fieldID).src = siteURL + 'avatars/microthumbs/1/' + imageID + '.png';
	}
	else
	{
		document.getElementById(fieldID).src = siteURL + 'avatars/microthumbs/' + userID + '/' + imageID + '.png';
	}
}

function toggleUserPictureGallery()
{

	$('#userPicturePreviewSurround').slideToggle('slow');
	$('#changeUserPictureSurround').slideToggle('slow');
	$('#userPictureGallerySurround').slideToggle('slow');
}

function confirmDeleteUserPicture()
{
	var response = confirm ('Are you sure you want to delete this user picture?  This action is irreversible.');
	if (response)
	{
		return true;
	}
	else
	{
		alert ('The user picture has not been deleted.');
		return false;
	}
}

var dontSave = false;
function autosaveMessage(cookieName, subject, to, bcc, message, timeout, autosavedMessageField)
{
	var timeNow = new Date();
	var expiresAt = new Date(timeNow.getTime() + (7 * 1000 * 60 * 60 * 24));

	if (!dontSave)
	{
		document.cookie = cookieName + '=' + escape(subject.value) + '@##@' + escape(to.value) + '@##@' + escape(bcc.value) + '@##@' + escape(message.value) + ';expires=' + expiresAt.toGMTString();

		autosavedMessageField.innerHTML = 'Draft autosaved: ' + timeNow.toGMTString();
	}

	setTimeout ('autosaveMessage("' + cookieName + '", document.getElementById("' + subject.id + '"), document.getElementById("' + to.id + '"), document.getElementById("' + bcc.id + '"), document.getElementById("' + message.id + '"), ' + timeout + ', document.getElementById("' + autosavedMessageField.id + '"));', timeout);
}

function saveMessage(cookieName, subject, to, bcc, message, timeout, autosavedMessageField)
{
	var timeNow = new Date();
	var expiresAt = new Date(timeNow.getTime() + (7 * 1000 * 60 * 60 * 24));

	document.cookie = cookieName + '=' + escape(subject.value) + '@##@' + escape(to.value) + '@##@' + escape(bcc.value) + '@##@' + escape(message.value) + ';expires=' + expiresAt.toGMTString();
	autosavedMessageField.innerHTML = 'Draft saved: ' + timeNow.toGMTString();

	return true;
}

function blankCookie(cookieName)
{
	var timeNow = new Date();
	var expiresAt = new Date(timeNow.getTime() - 10000);

	document.cookie = cookieName + '=;expires=' + expiresAt.toGMTString();
}

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function getCookie(check_name)
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split (';');
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for (i = 0; i < a_all_cookies.length; i++)
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split ('=');


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace (/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if (cookie_name == check_name)
		{
			b_cookie_found = true;

			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if (a_temp_cookie.length > 1)
			{
				cookie_value = unescape (a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}

			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	if (!b_cookie_found)
	{
		return null;
	}
}

function clearMessage(cookieName, clearDraftPhrase, draftClearedPhrase, draftRetainedPhrase)
{
	var response = confirm(clearDraftPhrase);
	if (response)
	{
		blankCookie(cookieName);
		alert (draftClearedPhrase);
		return true;
	}
	else
	{
		blankCookie(cookieName);
		alert (draftRetainedPhrase);
		return false;
	}
}

function restoreMessage(cookieName, subject, to, bcc, message, autosavedPhrase, messageRestoredPhrase, messageRemovedPhrase, nothingToRestorePhrase)
{
	var cookieDetails = getCookie(cookieName);
	var timeNow = new Date();
	var expiresAt = new Date(timeNow.getTime() - 1);
	if (cookieDetails != null && cookieDetails != 'undefined')
	{
		var arr = cookieDetails.split('@##@');
		if (arr.length == 4)
		{
			// This prevents the autosave from firing whilst the user is deliberating over their message box.
			dontSave = true;

			var response = confirm(autosavedPhrase);
			if (response)
			{
				subject.value = arr[0];
				to.value = arr[1];
				bcc.value = arr[2];
				message.value = arr[3];

				alert (messageRestoredPhrase);
			}
			else
			{
				alert (messageRemovedPhrase);
			}
			dontSave = false;
		}
		else
		{
			alert (nothingToRestorePhrase);
		}
	}
	else
	{
		alert (nothingToRestorePhrase);
	}
}

function reportPost(postID)
{
	var response = confirm ('Are you sure you want to report this post?');
	if (response)
	{
		window.location = '/contact/?report=post&postID=' + postID;
	}
	else
	{
		alert ('The post has not been reported.');
	}
	return false;
}

function reportThread(threadID)
{
	var response = confirm ('Are you sure you want to report this thread?');
	if (response)
	{
		window.location = '/contact/?report=thread&threadID=' + threadID;
	}
	else
	{
		alert ('The thread has not been reported.');
	}
	return false;
}

function sendStandardMessage(userID, messageID)
{
	if (document.getElementById('sendStandardMessage_' + messageID) && document.getElementById('sendStandardMessage_' + messageID) != 'undefined')
	{
		if (document.getElementById('sendStandardMessage_' + messageID).selectedIndex <= 1)
		{
			alert('You must choose a message to send!');
			document.getElementById('sendStandardMessage_' + messageID).focus();
			return false;
		}
		else
		{
			window.location = '/messages/send/standard/' + document.getElementById('sendStandardMessage_' + messageID).options[document.getElementById('sendStandardMessage_' + messageID).selectedIndex].value + '/to/' + userID + '/?replyTo=' + messageID;
			return true;
		}
	}
	else
	{
		alert('The message to which you are trying to send a standard response does not exist!');
		return false;
	}
}

function checkCreatePostForm()
{
 	
	if (document.getElementById('subject').value.length <= 0)
	{
		alert('You must enter a subject for your post before you can continue.');
		document.getElementById('subject').focus();
		return false;
	}
	
	if (document.getElementById('body').value.length <= 0)
	{
		alert('You must enter something to post before you can continue.');
		document.getElementById('body').focus();
		return false;
	}
	
/*	if	(document.getElementById('url1').value.length) {
		if (!isGoodURL(document.getElementById('url1').value)) {
			alert('url 1 is not in the correct format. URLS must start with http:// or https://');
			document.getElementById('url1').focus();
			return false;
		}
	}
	
	if	(document.getElementById('url2').value.length) {
		if (!isGoodURL(document.getElementById('url2').value)) {
			alert('url 2 is not in the correct format. URLS must start with http:// or https://');
			document.getElementById('url2').focus();
			return false;
		}
	}
	
	if	(document.getElementById('url3').value.length) {
		if (!isGoodURL(document.getElementById('url3').value)) {
			alert('url 3 is not in the correct format. URLS must start with http:// or https://');
			document.getElementById('url3').focus();
			return false;
		}
	}*/
	
	return true;
}
