/**
 * Global variables to hold HTTP Request for AJAX functions.
 */
var http_request;
var http_request2;

/**
 * Global variables to hold target element for AJAX functions.
 */
var el;
var e2;
var e3;
var e4;

/**
 * Adds a function to the window.onload event.
 * 
 * @author		http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 * @param	func	The name of the function to add.
 * @return		void.
 */
function addLoadEvent(func)
{    
    var oldonload = window.onload;
    if (typeof window.onload != 'function')
    {
        window.onload = func;
    } 
    else 
    {
        window.onload = function()
        {
            oldonload();
            func();
        }
    }
}

/**
 * Sets a cookie.
 * 
 * @author		http://www.netspade.com/articles/javascript/cookies.xml
 * @param	name	Name of cookie.
 * @param	value	Value of cookie.
 * @param	path	Path of cookie. (Optional.)
 * @param	domain	Domain of cookie. (Optional.)
 * @param	secure	Confine cookie to SSL? True/False. (Optional.)
 * @param	expires	Expiry date, RFC 822 date format. (Optional.)
 * @return		void.
 * @see 		#getCookie
 * @see 		#deleteCookie
 */
function setCookie(name, value, path, domain, secure, expires)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Read a cookie value.
 * 
 * @author		http://www.netspade.com/articles/javascript/cookies.xml
 * @param	name	Name of cookie.
 * @return		Value of the cookie. (String.)
 * @see 		#setCookie
 * @see 		#deleteCookie
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Forcibly expires a cookie. Sets the expiry date to 1970.
 * 
 * @author		http://www.netspade.com/articles/javascript/cookies.xml
 * @param	name	Name of cookie.
 * @param	path	Path of cookie.
 * @param	domain	Domain of cookie.
 * @return		void.
 * @see 		#getCookie
 * @see 		#setCookie
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/**
 * Format and validate a UK postcode.
 * 
 * @param	e	INPUT Element containing postcode.
 */
function format_postcode(e)
{
	el = e;
	var f = 'PostcodeGet';
	if (window.XMLHttpRequest)  // Mozilla, Safari, Opera, ...
		http_request = new XMLHttpRequest();
	
	else if (window.ActiveXObject)   // IE
		http_request = new ActiveXObject("Microsoft.XMLHTTP");

	http_request.onreadystatechange = function ()
	{
		if (http_request.readyState == 4)
		{
			if (http_request.status == 200)
			{
				r = http_request.responseText;
				if (r) el.value = r;
			}
		}
	}
	
	http_request.open('GET', '/public/extra/includes/inc_postcodes.php?ajax='+f+'&param='+e.value, true);
	http_request.send(null);
}

/**
 * Extend the native String class to include an array that lists silly
 * words that shouldn't be capitalised.
 */
String.noLC = new Object
  ({the:1, a:1, an:1, and:1, or:1, but:1, aboard:1,
    about:1, above:1, across:1, after:1, against:1,
    along:1, amid:1, among:1, around:1, as:1, at:1,
    before:1, behind:1, below:1, beneath:1, beside:1,
    besides:1, between:1, beyond:1, but:1, by:1, 'for':1,
    from:1, 'in':1, inside:1, into:1, like:1, minus:1,
    near:1, of:1, off:1, on:1, onto:1, opposite:1,
    outside:1, over:1, past:1, per:1, plus:1,
    regarding:1, since:1, than:1, through:1, to:1,
    toward:1, towards:1, under:1, underneath:1, unlike:1,
    until:1, up:1, upon:1, versus:1, via:1, 'with':1,
    within:1, without:1});

/**
 * Extend the native String class with a titleCase function.
 */
String.prototype.titleCase = function ()
{
	// Special case for just one word.
	if (!this.match(/(\s+)/))
		return this.substr(0,1).toUpperCase() + this.substr(1,this.length);

	// Multiple words, so split into words, storing whitespace safely.
	var gaps  = this.match(/(\s+)/g);
	var parts = this.split(/\s+/);
	if ( parts.length == 0 ) return '';

	var fixed = new Array();
	for ( var i in parts )
	{
		var fix = '';
		if ( String.noLC[parts[i]] )
			fix = parts[i].toLowerCase();

		else if ( parts[i].match(/^([A-Z]\.)+$/i) ) // will mess up "i.e." and like
			fix = parts[i].toUpperCase();
			
		else if ( parts[i].match(/^[^aeiouy]+$/i) ) // voweless words are almost always acronyms
			fix = parts[i].toUpperCase();

		else
			fix = parts[i].substr(0,1).toUpperCase() +
			       parts[i].substr(1,parts[i].length);

		fixed.push(fix);
	}
	
	fixed[0] = fixed[0].substr(0,1).toUpperCase() +
        	       fixed[0].substr(1,fixed[0].length);
	
	var out = '';       
	for ( var i in fixed )
	{
		if (gaps[i])
			out += fixed[i] + gaps[i];
		else
			out += fixed[i];
	}
	return out;
}

/**
 * Extend the native String class with a snip function to trim whitespace.
 */
String.prototype.snip = function ()
{
	return this.replace(/^\s+|\s+$/g, '');
}

/**
 * Format into UPPER-CASE.
 * 
 * @param	e	INPUT Element to be formatted.
 * @see 		#format_case_lower
 * @see 		#format_case_title
 */
function format_case_upper(e)
{
	e.value = e.value.toUpperCase().snip();
}

/**
 * Format into lower-case.
 * 
 * @param	e	INPUT Element to be formatted.
 * @see 		#format_case_upper
 * @see 		#format_case_title
 */
function format_case_lower(e)
{
	e.value = e.value.toLowerCase().snip();
}

/**
 * Format into Title-Case.
 * 
 * @param	e	INPUT Element to be formatted.
 * @see 		#format_case_upper
 * @see 		#format_case_lower
 */
function format_case_title(e)
{
	e.value = e.value.titleCase().snip();
}

/**
 * Sets the value on a SELECT element to an NCT branch number, based
 * on a postcode.
 * 
 * @param	pc	Postcode string.
 * @param	e	SELECT element to set..
 */
function branch_select_by_postcode(e, pc)
{
	e4 = e;
	
	if (window.XMLHttpRequest)  // Mozilla, Safari, Opera, ...
		http_request2 = new XMLHttpRequest();
	
	else if (window.ActiveXObject)   // IE
		http_request2 = new ActiveXObject("Microsoft.XMLHTTP");

	http_request2.onreadystatechange = function ()
	{
		if (http_request2.readyState == 4)
		{
			if (http_request2.status == 200)
			{
				r = http_request2.responseText;
				if (r)
					for(var i=0; e4.options[i]; i++)
						if (e4.options[i].value==r.snip())
							e4.selectedIndex=i;
			}
		}
	}
	
	http_request2.open('GET', '/public/extra/scripts/ajax_findbranch?pc='+pc);
	http_request2.send(null);
}

/**
 * Makes the "print" link on each page functional. Should be called when
 * page first loads.
 *
 * @see 		#addLoadEvent
 */
function initPrintDynamo()
{
	var print = document.getElementById('dynamo_print');
	print.innerHTML = '[<a href="#" onclick="window.print()" title="Print this page">print<\/a>]';
}
// addLoadEvent(initPrintDynamo);

var TitleStorer;

function txtTitleMagic ()
{
	var T = document.getElementById('txtTitle');
	if (!T) return 0;

	TitleStorer = T.innerHTML;	
	var t;
	var tits = T.getElementsByTagName('OPTION');
	for(var i=0; tits[i]; i++)
	{
		t = tits[i].value;
//		window.alert(t);
		if (t=='Dr'||t=='Mr'||t=='Mrs'||t=='Ms'||t=='Miss')
		{
			// nothing
		}
		else
		{
			T.removeChild(tits[i]);
			i--;
		}
	}
	t2 = document.createElement('OPTION');
	t2.innerHTML = 'More...';
	t2.value = 'Ms';
	T.appendChild(t2);
	T.onchange = txtTitleMagic2;
}

function txtTitleMagic2 ()
{
	var T = document.getElementById('txtTitle');
	if (T.options[T.selectedIndex].innerHTML=='More...')
		T.innerHTML = TitleStorer;
}

addLoadEvent(txtTitleMagic);

function checkStage1frm ()
{
	var v1 = document.getElementById('txtForename').value;
	var v2 = document.getElementById('txtSurname').value;
	var v3 = document.getElementById('txtPostcode').value;

	if (v1.length==0|| v2.length==0 || v3.length==0)
	{
		window.alert("Please fill in the form.");
		return false;
	}
}

