

var xmlHttpRequestObject = getXmlHttpRequestObject();
var item_added_callback = null;



function shopping_cart_add_item(product_id, _item_added_callback)
{
    //If our XmlHttpRequest object is not in the middle of a request, start the new asyncronous call.
    if (xmlHttpRequestObject.readyState == 4 || xmlHttpRequestObject.readyState == 0)
    {
	item_added_callback = _item_added_callback;

	// Setup the connection as a GET call
	// True explicity sets the request to asyncronous (default).
	var url = "../ajax/add_item_to_cart.php?product_id=" + product_id;
	xmlHttpRequestObject.open("GET", url, true);

	//Set the function that will be called when the XmlHttpRequest objects state changes.
	xmlHttpRequestObject.onreadystatechange = shopping_cart_item_added; 

	//Make the actual request.
	xmlHttpRequestObject.send(null);
    }			
}


function shopping_cart_item_added()
{
    //Check to see if the XmlHttpRequests state is finished.
    if (xmlHttpRequestObject.readyState != 4)
    {
	return;
    }

    // pass the result of the asyncronous call to the callback function
    item_added_callback(xmlHttpRequestObject.responseText);
}


function shopping_cart_refresh_items_text(items_text)
{
   //Set the contents of our span element to the new number of items text
    document.getElementById("num_shopping_cart_items").innerHTML = items_text;
}


function add_item_callback(response_text)
{
    switch (response_text)
    {
    case "OK":
	item_added_ok();  // this should be defined in a page specific js file (e.g., product_catalog.js)
	break;

    case "Unavailable":
	item_unavailable();
	break;
	
    default:
	item_added_unknown_error(response_text);
	break;
    }
}


function item_unavailable()
{
    alert("The item is no longer available.\nClick Refresh to see available items.");
}


function item_added_unknown_error(error_message)
{
    alert("An unexpected error occurred.\nError message: " + error_message);
}
