// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// holds the remote server address and parameters
var cart_totals_page = "cart_totals.php";
var cart_add_page = "cart_add.php";
// variables used to check for server availability 
var requestsCounter = 0; // counts how many numbers have been retrieved
var checkInterval = 10; // counts interval for checking server availability
var updateInterval = 1; // how many seconds to wait to get a new number
var updateIntervalIfServerBusy = 10; // seconds to wait when server busy
var minServerBufferLevel = 50; // what buffer level is considered acceptable
var errorRetryInterval = 30; // seconds to wait after server error


// function that displays an error message
function displayError($message)
{
	 var showErrors = true;
	 // ignore errors if showErrors is false
	 if (showErrors)
	 {
		// turn error displaying Off
		showErrors = false;
		// display error message
		alert("Error encountered: \n" + $message);
	
	  }
}
// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

// call server asynchronously
function update_cart_totals($cart_session_id)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {   // get cart totals
        xmlHttp.open("GET", cart_totals_page + "?cart_id=" + $cart_session_id, true);
        xmlHttp.onreadystatechange = handleCartTotals;
        xmlHttp.send(null);
    }
    catch(e)
    {
      // display error message
      alert("Can't connect to server.");
    }
  }
}

// function that displays a new message on the page
function displayCart_Totals($p_items, $p_total)
{
  // obtain a reference to the <div> element on the page
  cart_items_div = document.getElementById("div_cart_items");
  cart_items_div.innerHTML += "$" + $p_items + "<br/>";
  cart_totals_div = document.getElementById("div_cart_total");
  cart_totals_div.innerHTML += "$" + $p_total + "<br/>";
}

// function that displays a new message on the page
function displayCart($p_cart_message)
{
  // obtain a reference to the <div> element on the page
  cart_items_div = document.getElementById("div_cart");
  cart_items_div.innerHTML = $p_cart_message + "<br/>";
}

// function called when the state of the HTTP request changes
function handleCartTotals() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the reponse from the server
        get_cart_totals_response();
      }
      catch(e)
      {
        // display error message
        displayError("Error reading server availability (CATCH), xmlHttp status: " + xmlHttp.status + " status text: " + xmlHttp.statusText);
      }
    } 
    else
    {
      // display status message
      displayError("Error reading server availability (ELSE), xmlHttp status: " + xmlHttp.status + " status text: " + xmlHttp.statusText);         
    }
  }
}

// handles the response received from the server
function get_cart_totals_response()
{
    var response = xmlHttp.responseText;
  // if the response is long enough, we assuwe we just received
  // a server-side error report
  if(response.length > 5) {
	  if ((response.substring(0,1)) == "<") {
		  displayCart(response);
	  } 
	  else {
		  alert(response);
	  }
  }
  else {
	  alert(response);
  }
 
}

// call server asynchronously
function add_to_cart($cart_session_id, $isrc_code)
{
  //alert('ID: ' + $cart_session_id + ' - ISRC Code: ' + $isrc_code);
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {   // get cart totals
        xmlHttp.open("GET", cart_add_page + "?cart_id=" + $cart_session_id + "&isrc_code=" + $isrc_code, true);
        xmlHttp.onreadystatechange = handle_cart_add;
        xmlHttp.send(null);
    }
    catch(e)
    {
      // display error message
      alert("Can't connect to server.");
    }
  }
}


// function called when the state of the HTTP request changes
function handle_cart_add() 
{
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) 
  {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the reponse from the server
        get_cart_add_response();
      }
      catch(e)
      {
        // display error message
        displayError("Error reading server availability [1], will retry after ");
      }
    } 
    else
    {
      // display status message
      displayError("Error reading server availability [2], will retry after ");           
    }
  }
}

// handles the response received from the server
function get_cart_add_response()
{
  // retrieve the server's response 
  var response = xmlHttp.responseText;
  // if the response is long enough, we assuwe we just received
  // a server-side error report
  if(response.length > 5) {
	  if ((response.substring(0,1)) == "<") {
		  display_add_cart_reponse(response);
	  } 
	  else {
		  alert(response);
	  }
  }
  else {
	  alert(response);
  }
}

// function that displays a new message on the page
function display_add_cart_reponse($p_cart_message)
{
  // obtain a reference to the <div> element on the page
  cart_items_div = document.getElementById("div_cart");
  cart_items_div.innerHTML = $p_cart_message + "<br/>";
}

