﻿	var	apiurl				=	'/resources/php/ajaxcall.php';

	// Turn on/off debug alerts
	var	debugbba			=	0;

	// 0	= clear to send
	// 1	= waiting
	// -1	= fatal http error
	// -2	= no postcode given
	var	ajaxStatus			=	0;

	tcinit();


function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}
	// ------------------------------------------------------
	// 
	// Main function and support functions
	// 
	// The function called to start everthing going once
	// the user has requested a check
	// 
	// ------------------------------------------------------

	/**
	 * Initialization function
	 */
	 
	function tcinit() {
		ajaxStatus			=	0;
	}
  
  	/**
  	 * Called to start everthing going
  	 *
  	 * @param		String			dataquerystring
  	 * @param		Function		Function to call when call begins
  	 * @param		Function		Function to call when data is ready
  	 * @param		Function		Function to call if there is a fatal error attempting to call
  	 *
  	 * @return		Boolean			false
  	 */
  	 
	function ajax_submit( dataquerystring, start_callback, end_callback, error_callback ) {


		if( ajaxStatus )		{	return false;	}

		if( dataquerystring )	{
	
			// Waiting
			ajaxStatus = 1;

			var xmlhttp =	getHttpRequestObj();
			xmlhttp.open('POST', apiurl, true);
			xmlhttp.onreadystatechange = function() {

				if (xmlhttp.readyState == 4) {
					if (xmlhttp.status == 200)	{

						// On return, get the data and call user function
						xdata	=	getTextDoc( xmlhttp );
						responceComplete( xdata, end_callback, target);
					}
					else	{
						// Fatal error
						ajaxStatus	=	-1;
					}
				}
			}
	
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.send( dataquerystring );
		}
		else	{
			ajaxStatus	=	-2;
		}

		if( ajaxStatus< 0 )	{
			if( error_callback )	{
				eval(error_callback)(error_callback, ajaxStatus);
			}
		}
		else	{
			if( start_callback )	{
				eval(start_callback)(target);
			}
		}

		// Stop the form for going anywhere
		return	false;
	}


	/**
	 * Called when data has returned from samknows
	 *
	 * @param		Object		document
	 * @param		Function	Callback to call
	 * @param		Object		Target ... unused
	 *
	 */
	 
	function responceComplete( data, end_callback, target ) {

		ajaxStatus = 0;

		if( end_callback )	{
			eval( end_callback)( data );
		}
	}

	/**
	 * Platform independant XMLHttpRequest getter
	 *
	 * @return		Object		XMLHttpRequest/ActiveX object
	 */

	function	getHttpRequestObj()	{

		if( window.XMLHttpRequest )	{
			var xmlhttp =	new XMLHttpRequest();
		}
		else	{
			var xmlhttp =	new ActiveXObject("MSXML2.XMLHTTP.3.0");
		}
		
		return	xmlhttp;
	}


	function	getTextDoc( xmlhttp )	{
		return	xmlhttp.responseText;
	}

