// Asynchronous Javascript
// js/async.js
// Richard Crowley
// 3.12.2006

// Hit a page in the background and call action to handle the results
function async_hit( url, action ) {
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject( 'Microsoft.XMLHTTP' );
	}
	req.onreadystatechange = function () {
		if ( 4 == req.readyState && 200 == req.status ) {
			action( req.responseText );
		}
	};
	req.open( 'GET', url, true );
	req.send( null );

}



// Post to a page in the background
function async_post( url, data, action ) {
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		req = new ActiveXObject( 'Microsoft.XMLHTTP' );
	}
	req.onreadystatechange = function () {
		if ( 4 == req.readyState && 200 == req.status ) {
			action( req.responseText );
		}
	};
	req.open( 'POST', url, true );
	req.setRequestHeader( 'Content-type',
	                      'application/x-www-form-urlencoded' );
	req.setRequestHeader( 'Content-length', data.length );
	req.setRequestHeader( 'Connection', 'close');
	req.send( data );
}

// Rate a place
function rate( id, thumb ) {
	async_hit( '/rate/?id=' + id + '&thumb=' + thumb,
	function( raw ) {
		var data = new String( raw );
		var arr = new Array();
		arr = data.split( ' ' );
		if ( 3 != arr.length ) { return; }
		document.getElementById( 'up_' + arr[0] ).innerHTML = arr[1];
		document.getElementById( 'down_' + arr[0] ).innerHTML = arr[2];
		document.getElementById( 'rate_up_' + arr[0] ).innerHTML =
		  'Thumbs Up';
		document.getElementById( 'rate_down_' + arr[0] ).innerHTML =
		  'Thumbs Down';
	} );
}

function check_addy ( ) {
	var email=document.getElementById("email").value;
	async_hit ('check_email.php?email=' + email, 
	function ( raw ) {
		if (raw=="1")
		{
			document.getElementById("form").innerHTML= "<div style='border: 2px solid #00ff00; background-color: #aaffaa; padding: 2px;'>Your email address \"" + email + "\" has been added to our mailing list!</div>";
		}
		else if (raw=="0")
		{
			document.getElementById("mail_error").innerHTML= "The email address you have submitted was not valid. Please fix the error and try again.";
			document.getElementById("mail_error").style.display="block";
		}
		else if (raw=="2")
		{
			document.getElementById("form").innerHTML= "<div style='border: 2px solid #00ff00; background-color: #aaffaa; padding: 2px;'>Your email address \"" + email + "\" is already on our mailing list!</div>";
		}
		else if (raw=="3")
		{
			document.getElementById("mail_error").innerHTML= "The server encountered an error while processing your request. Please try again later.";
			document.getElementById("mail_error").style.display="block";
		}
		
	} );
}

function get_post_content ( id )
{
	var resp;
	resp = async_hit ('getpost.php?id=' + id,
	function (raw) 
	{
		resp=raw.parseJSON();
		return resp;
	} );
	return resp;
}

