/*=======================================================================
 *
 * (c) 2006 Ben Schwartz ( benschw@gmail.com | benhschwartz.com )
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *

 *
 * Notes:
 *  the argument "classname" is reserved
 *
 *
 *
 *
 *
 *=====================================================================*/



function AjaxRequest( className ) {

	this.request 				= null;
	this.fcn 						= function() {};					// called as state changes
	this.url 						= 'ajaxserver.xml.php';		// my server script, handles all requests
	this.args						= null; 	// becomes array of key/val hashes
	this.status 				= false;	// status block handle, false if no status shown
	this.message 				= null;		// loading message for status block
	this.successMessage = '';			// message for status block after successful transaction
	this.failureMessage	= false;			// message for status block after failed transaction
	
	// accessors ================================================

	this.getRequest 		= function() 				{	return this.request;															};
	
	this.setResponse 		= function( fcn ) 	{	this.fcn = fcn;																		};
	this.setServerClass	= function( name ) 	{	this.addArg( 'classname', name );									};

	this.setStatusId		= function( id )		{	this.status = document.getElementById( id );			};
	this.setMsg					= function( msg )		{ this.message = msg;																};
	this.setSuccessMsg	= function( msg )		{ this.successMessage = msg;												};
	this.setFailureMsg	= function( msg )		{ this.failureMessage = msg;												};

	// accessors on result data =================================

	this.getXml					= function() 				{ return this.request.responseXML.documentElement;	};
	this.getText				= function()				{ return this.request.responseText									};

	this.getTag 				= function( tag ) 	{ 
		
		if( this.getXml().getElementsByTagName( tag )[0].firstChild ) {
			return this.getXml().getElementsByTagName( tag )[0].firstChild.data;	
		} else {
			return '';
		}
	};
	this.getChildTag 		= function( handle, tag ) 	{ 
		
		if( handle.getElementsByTagName( tag )[0].firstChild ) {
			return handle.getElementsByTagName( tag )[0].firstChild.data;	
		} else {
			return '';
		}
	};

	// handle arguments =========================================
	
	this.addArg = function( key, val ) { // push new key/val pair onto arg array
		if( this.args == null )
			this.args = new Array();
	
		var tmp = new Array();
		tmp['key'] = key;
		tmp['val'] = val;
		this.args[this.args.length] = tmp;
	};

	this.getArgString = function() {		// implode arguments into string for sending
		if( this.args != null ) {
			var string = '';
			for( var i = 0; i < this.args.length; i++ ) {	
				if( i != 0 )
					string += '&';
				string += this.args[i]['key'] + '=' + this.args[i]['val'];
			}
			return string;
		} else {
			return null;
		}
	};	

	// send it off ==============================================

	this.send = function( method ) {		// send off request as GET or POST
		this.request.onreadystatechange = this.fcn;
		if( method.toLowerCase() == 'post' ) {
			this.request.open( "POST", this.url, true );
			this.request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
			this.request.send( this.getArgString() );
		} else {
			if( this.args != null )
				var getUrl = this.url + '?' + this.getArgString();
			else
				var getUrl = this.url;
			this.request.open( "GET", getUrl, true );
			this.request.send( null );
		}
	};

	// test state and show status ===============================

	this.checkReadyState = function() {

		if( this.request.readyState == 0 ) {  } // uninitialized
		if( this.request.readyState == 1 ) { 		// loading
			if( this.status ) {
				this.status.innerHTML = '<div style="height:20px;padding:2px;"><img height="1em" style="margin-right:10px;" src="images/wait.gif" />' + this.message + '</div>'; 
			}
		} 
		if( this.request.readyState == 2 ) {  } // loaded
		if( this.request.readyState == 3 ) {  } // interactive
		if( this.request.readyState == 4 )			// complete
		{
	
			if(this.request.status == 200) {					// success
				if( this.status ) {
//					new Effect.Pulsate( this.status.id );
					this.status.innerHTML = this.successMessage;
				}
				return true;
			} else {

				if( this.failureMessage ) {
					if( this.status )
						this.status.innerHTML = this.failureMessage;
					else
						alert( this.failureMessage );

				} else if( this.request.status == 404 ) {		// trouble retrieving xml file

					if( this.status )
						this.status.innerHTML = "Requested File Not Found.";
					else
						alert( "Requested File Not Found." );

				} else {																	// other error
					if( this.status )
						this.status.innerHTML = "Error "+this.request.status+": "+this.request.statusText;
					else 
						alert( "Error "+this.request.status+": "+this.request.statusText );
				}

				return false;
			}
		}
	};

	// constructor ================================================	

	this.setServerClass( className );

	if(window.XMLHttpRequest) {
		this.request = new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		this.request = new ActiveXObject("MSXML2.XMLHTTP");
	}


}

