// *****************************************************************************
// AJAX JAVASCRIPT CLASS
// Copyright 2006 by Timothy Anido <xanido@gmail.com>
// ***************************************************************************** 
/*
	USAGE:

	myajax = new ajax( 'url' );
	myajax.onLoading = function;
	myAjax.onSuccess = function;
	myAjax.sendQeury( 'query=string' );
*/

var ajax = Class.create( );
ajax.prototype = {
	
	connector : null,
	onLoading : function() { },
	onSuccess : function() { },
	receiver: null,
	response: null,
	
	initialize : function( receiver )
	{
		if (window.ActiveXObject) connector = new ActiveXObject('Microsoft.XMLHTTP');
		else if (window.XMLHttpRequest) connector = new XMLHttpRequest();
		this.connector = connector;
		if( receiver ) this.receiver = receiver;
	},
	
	sendRequest : function( query )
	{
		if( this.loading( ) == 1 ) return;
		
		d = new Date();
		t = d.getYear() * d.getMonth() * d.getDay() * d.getHours() * d.getMinutes() * d.getSeconds();
		
	    this.connector.open('get', this.receiver+"?"+t+"&"+query);
	    this.connector.onreadystatechange = this.stateChange.bind(this);
	    this.connector.send(null);
	},
	
	stateChange : function( )
	{
		if(this.connector.readyState == 1) { this.onLoading(); }
		if(this.connector.readyState == 4) { this.response = this.connector.responseText; this.onSuccess( this.response ); }
	},
	
	loading : function( )
	{
		return this.connector.readyState;
	}

}

var ajax = new ajax( 'ajax.php' );
var tmp_id, tmp_status;
function updateCart( id, action ){
	if( action == 'add' )
	{
		num = prompt("How many would you like to add to your cart?","1");
		if( num == null || num == "" ) return;
	} else { num = 0; }
	tmp_id = id;
	tmp_action = action;
	ajax.onLoading = updating;
	ajax.onSuccess = updateComplete;
	ajax.sendRequest( 'action=update_cart&id='+id.toString( )+'&act='+action+'&num='+num.toString( ) );
}

function updating( )
{
	$(tmp_id + '_cart_image').src = 'img/loading.gif';
}

function updateComplete( )
{
	if( tmp_action == 'add' ) tmp = ['delete','removed','selected']; else tmp = ['add', 'added', ''];
	$(tmp_id + '_cart_image').src = 'img/cart_' + tmp[0] + '.gif';
	$(tmp_id + '_cart_action').tmp_id = tmp_id;
	$(tmp_id + '_cart_action').onclick = function() { updateCart( this.tmp_id, tmp[0] ); return false };
	$(tmp_id + '_row').className = tmp[2];
	
}