/*
status is stored in edit-amazoncheck-status
	0 => NONE (original value)
	1 => SEARCHING
	2 => SUCCESS
	3 => FAILURE

The value in edit-amazoncheck-serviceurl must match the host/port/protocol of the page which uses this..
*/
function setBookType(name) {
		$('add-type').setAttribute('value', name);
}

function doFill() {
	amazonCheck();
	return false;
}


function amazonCheck() {

	var url = $('edit-amazoncheck-serviceurl').getValue();
	var userASIN = $('amz_book_isbn').getValue();

	if ( !userASIN || userASIN.length < 10 ) {
		alert( "Please enter an ISBN/ASIN (at least ten characters)" );
		return;
	}

	$('edit-amazoncheck-status').setAttribute( 'value', 1 );	//	SEARCHING

	Form.Element.disable( "amz_book_isbn" );

	new Ajax.Request( url,
	{
		method:'get',
		parameters: { asin: userASIN },
		onSuccess: function( transport ) {

			Form.Element.enable( "amz_book_isbn" );

			var title = null;
			var author = null;
			var year = null;
			var publisher = null;
			var message = null;

			try {
				s = "(" + transport.responseText + ")";
				obj = eval( s );
				title = ( obj[ 'title' ] == undefined ? '' : obj[ 'title' ] );
				author = ( obj[ 'author' ] == undefined ? '' : obj[ 'author' ] );
				year = ( obj[ 'publicationYear' ] == undefined ? '' : obj[ 'publicationYear' ] );
				publisher = ( obj[ 'publisher' ] == undefined ? '' : obj[ 'publisher' ] );
				message = ( obj[ 'message' ] == undefined ? '' : obj[ 'message' ] );
			}
			catch (e) {
				alert( 'eval exception ' + e + ', s=' + s );
			}

			if ( null == title || ( message != null && message.length > 1 ) ) {
				$('edit-amazoncheck-status').setAttribute( 'value', 3 );	//	FAILURE
			}
			else {
				$('edit-amazoncheck-status').setAttribute( 'value', 2 );	//	SUCCESS
				$('amz_book_title').setAttribute( 'value', title );
				$('amz_book_author').setAttribute( 'value', author );
				$('amz_book_year').setAttribute( 'value', year );
				$('amz_book_publisher').setAttribute( 'value', publisher );
			}
			$('autoform').submit();
		},

		onFailure: function() {

			Form.Element.enable( "amz_book_isbn" );
			$('edit-amazoncheck-status').setAttribute( 'value', 3 );	//	FAILURE
			//setTimeout( function() {
			$('autoform').submit();
		}
	});
}