/*
 * $Id$
 *
 * AJAX functions for handling cart operations.
 *
 * (c) Copyright WebImplements 2009.  All rights reserved.
 */

AJAX_TARGET = '/index.php?';

/*
 * Make an AJAX call specifying the URL and the response handling function
 * 
 * @param  url  the URL
 * @param  f    the function handling the response
 */
function ajaxCall(url, f)
{
  var xmlHttp;
  try
  {
    // Firefox, Opera 8.0+, Safari
    xmlHttp = new XMLHttpRequest();
  }
  catch (e)
  {
    // Internet Explorer
    try
    {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      try
      {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

  /*   */
  xmlHttp.onreadystatechange = function()
  {
    if (xmlHttp.readyState == 4)
    {
      f(xmlHttp);
    }
  };

  xmlHttp.open("GET", url, true);
  xmlHttp.send(null);
}

/*
 * Add specified product to cart
 * 
 * @param  offerid  the offer ID
 * @param  aid      the ASIN
 */
function add(offerid, aid)
{
  ajaxCall(AJAX_TARGET + "a=" + encodeURI(offerid) + "&asin=" + encodeURI(aid),
    function(xmlHttp)
    {
      targetDiv = document.getElementById('cart-content');
      targetDiv.innerHTML = xmlHttp.responseText;
    });
}

/*
 * Remove specified product from cart
 * 
 * @param  itemid  the item ID
 */
function remove(itemid)
{
  ajaxCall(AJAX_TARGET + "r=" + encodeURI(itemid),
    function(xmlHttp)
    {
      targetDiv = document.getElementById('cart-content');
      targetDiv.innerHTML = xmlHttp.responseText;
    });
}

/*
 * Modify product quantity in cart
 * 
 * @param  itemid  the item ID
 * @param  qty     the quantity 
 */
function modify(itemid, qty)
{
  ajaxCall(AJAX_TARGET + "mq=" + encodeURI(itemid) + "&q=" + encodeURI(qty),
    function(xmlHttp)
    {
      targetDiv = document.getElementById('cart-content');
      targetDiv.innerHTML = xmlHttp.responseText;
    });
}

/*
 * View cart content 
 */
function view()
{
  ajaxCall(AJAX_TARGET + "v",
    function(xmlHttp)
    {
      targetDiv = document.getElementById('cart-content');
      targetDiv.innerHTML = xmlHttp.responseText;
    });
}

/*
 * Clear cart content 
 */
function clear()
{
  ajaxCall(AJAX_TARGET + "c",
    function(xmlHttp)
    {
      targetDiv = document.getElementById('cart-content');
      targetDiv.innerHTML = xmlHttp.responseText;
    });
}

