/* cartURL - URL for updating cart Items */
var cartURL = "cart.php";

var xmlHttp = createXmlHttpRequestObject();

/* 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 Item
  if (!xmlHttp)
    alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

function addItem(idItem)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    {
      var idPcodeElement = 'pcode_' + idItem;
	  var idQtyElement = 'ackinput_qty_' + idItem;
      var pcode = document.getElementById(idPcodeElement).value;
	  var quantity = document.getElementById(idQtyElement).value;
      // create the params string
      var params = "?pcode=" + pcode + "&quantity=" + quantity + "&action=add&mode=lt";
	  //var params = "";
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	  xmlHttp.onreadystatechange = handleRequestStateChange;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      //alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function removeItem(tab_index, idItem)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    { //var index = obj.parentNode.parentNode.parentNode.parentNode.tabIndex
      var idPcodeElement = 'pcode_hidden_' + idItem;
	  var idQtyElement = 'qty_hidden_' + idItem;
      var pcode = document.getElementById(idPcodeElement).value;
	  var quantity = document.getElementById(idQtyElement).value;
      // create the params string
      var params = "?pcode=" + pcode + "&quantity=" + quantity + "&action=remove&tab_index=" + tab_index;
	  //var params = "";
	  //alert(params);
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	   xmlHttp.onreadystatechange = handleRequestStateChange_rm;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function setItem(idItem)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    { //var index = obj.parentNode.parentNode.parentNode.parentNode.tabIndex
      var idPcodeElement = 'pcode_hidden_' + idItem;
	  	var idQtyElement = 'ackinput_qty_' + idItem;
      var pcode = document.getElementById(idPcodeElement).value;
	  	var quantity = document.getElementById(idQtyElement).value;
      // create the params string
      var params = '?pcode=' + pcode + '&quantity=' + quantity + '&action=set&id_hidden=' + idItem;
	  	//var params = "";
	  	//alert(params);
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	  	xmlHttp.onreadystatechange = handleRequestStateChange_set;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function set_shipment(idItem)
{ 
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    { //var index = obj.parentNode.parentNode.parentNode.parentNode.tabIndex
      //var idShipment = document.getElementById("shipment").value;
		for (var i=0; i < document.frmSpedizioni.id_ship.length; i++){
			if (document.frmSpedizioni.id_ship[i].checked){
				var idShipment = document.frmSpedizioni.id_ship[i].value;
			}
		}
	  
      // create the params string
      var params = '?action=addShipment&id_ship=' + idShipment;
	  
	  //alert(params);
      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	   xmlHttp.onreadystatechange = handleRequestStateChange_ship_pay;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function set_payment(idItem)
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    { //var index = obj.parentNode.parentNode.parentNode.parentNode.tabIndex
      //var idPayment = document.getElementById("payment").value;
		for (var i=0; i < document.frmPagamenti.id_payment.length; i++){
			if (document.frmPagamenti.id_payment[i].checked){
				var idPayment = document.frmPagamenti.id_payment[i].value;
			}
		}
	  	//alert(idPayment);
      // create the params string
      //alert("idPayment "+idPayment);
      var params = '?action=addPayment&id_payment=' + idPayment;
	  	//alert(params);

      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	  	xmlHttp.onreadystatechange = handleRequestStateChange_ship_pay;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

function set_shipment_payment()
{
  // only continue if xmlHttp isn't void
  if (xmlHttp)
  {
    // try to connect to the server
    try
    { 
    	for (var i=0; i < document.frmPagamenti.id_payment.length; i++){
			if (document.frmPagamenti.id_payment[i].checked){
				var idPayment = document.frmPagamenti.id_payment[i].value;
			}
		}
		
		for (var i=0; i < document.frmSpedizioni.id_ship.length; i++){
			if (document.frmSpedizioni.id_ship[i].checked){
				var idShipment = document.frmSpedizioni.id_ship[i].value;
			}
		}
		
      var params = '?action=addShipmentPayment&id_payment=' + idPayment + '&id_ship=' + idShipment;
      //alert(params);

      // initiate the asynchronous HTTP request
      xmlHttp.open("GET", "cart.php" + params, true);
	  	xmlHttp.onreadystatechange = handleRequestStateChange_ship_pay;
      xmlHttp.send(null);
    }
    // display the error in case of failure
    catch (e)
    {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

// function called when the state of the HTTP request changes
function handleRequestStateChange_set() 
{
  if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3) 
  {
	document.body.style.cursor = 'wait';
  }
  // when readyState is 4, we are ready to read the server response  
  if (xmlHttp.readyState == 4) 
  { //alert(xmlHttp.status);
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse_set();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

// function called when the state of the HTTP request changes
function handleRequestStateChange_rm() 
{
  if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3) 
  {
	document.body.style.cursor = 'wait';
  }
  // when readyState is 4, we are ready to read the server response  
  if (xmlHttp.readyState == 4) 
  { //alert(xmlHttp.status);
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse_rm();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

function handleRequestStateChange_ship_pay() 
{
  if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3) 
  {
	document.body.style.cursor = 'wait';
  }
  // when readyState is 4, we are ready to read the server response  
  //alert(xmlHttp.readyState);
  if (xmlHttp.readyState == 4) 
  { //alert(xmlHttp.status);
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse_ship_pay();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

// function called when the state of the HTTP request changes
function handleRequestStateChange() 
{
  if (xmlHttp.readyState == 1 || xmlHttp.readyState == 2 || xmlHttp.readyState == 3) 
  {
	document.body.style.cursor = 'wait';
  }
  // when readyState is 4, we are ready to read the server response  
  if (xmlHttp.readyState == 4) 
  { //alert(xmlHttp.status);
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) 
    {
      try
      {
        // do something with the response from the server
        handleServerResponse();
      }
      catch(e)
      {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } 
    else
    {
      // display status message
      alert("There was a problem retrieving the data:\n" + 
            xmlHttp.statusText);
    }
  }
}

// handles the response received from the server
function handleServerResponse()
{
  // retrieve the server's response packaged as an Text object
  var Response = xmlHttp.responseText;
  // catching potential errors with IE and Opera
  if (Response.length == 0)
    throw("Invalid XML structure:\n" + xmlHttp.responseText);
 
	//document.getElementById("cart").scrollIntoView(true);
	fadeup("cart",255,126,153);

	var box_carrello = document.getElementById("cart_box");
	if (box_carrello.className == "hidden")
	{
		box_carrello.className = "box";
	}
	// display*/
	myDiv = document.getElementById("cart_content");
	myDiv.innerHTML = Response ;
	document.body.style.cursor = 'auto';
}

// handles the response received from the server
function handleServerResponse_rm()
{
  try{
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;
  //catturo errori con IE e opera
  if (!xmlResponse || !xmlResponse.documentElement){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  //catturo gli errori con Firefox
  var rootNodeName = xmlResponse.documentElement.nodeName;
  if (rootNodeName == "parsererror"){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;  
  // obtain arrays with book titles and ISBNs 
  totalArray = xmlRoot.getElementsByTagName("total");
  pesArray = xmlRoot.getElementsByTagName("pes");
  //partialArray = xmlRoot.getElementsByTagName("partial");
  tab_indexArray = xmlRoot.getElementsByTagName("tab_index");
  numArray = xmlRoot.getElementsByTagName("num");

	// display
	var num_item = numArray.item(0).firstChild.data;
	
	var rIndex = tab_indexArray.item(0).firstChild.data;
	var basket_tab = document.getElementById("BasketTab");
	//cancello la riga
	basket_tab.deleteRow(rIndex);

	if (num_item != 0){
		//var parziale = partialArray.item(0).firstChild.data;
		var totale = totalArray.item(0).firstChild.data;
		var peso = pesArray.item(0).firstChild.data;
	} else {
		var totale = "0,00";
		var peso = "0";
	}
	
	if (num_item == 0){
		//cancello testata
		basket_tab.deleteRow(0);
		document.getElementById("basket_msg").className = 'visible';
		document.getElementById("totale").innerHTML = totale + ' €';
		document.getElementById("peso").innerHTML = peso;
		//document.getElementById("pulsanti").innerHTML = '';
	}else{
		document.getElementById("totale").innerHTML = totale + ' €';
		document.getElementById("peso").innerHTML = peso;
		//document.getElementById("parziale").innerHTML = '€' + parziale;
	}
	document.body.style.cursor = 'auto';
	} catch (e){
		alert("!!!!: " + e.toString());
	}
	/*if (num_item > 0){
		set_shipment();
	}*/
}

// handles the response received from the server
function handleServerResponse_set()
{
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;
  //catturo errori con IE e opera
  if (!xmlResponse || !xmlResponse.documentElement){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  //catturo gli errori con Firefox
  var rootNodeName = xmlResponse.documentElement.nodeName;
  if (rootNodeName == "parsererror"){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;  
  totalArray = xmlRoot.getElementsByTagName("total");
  pesArray = xmlRoot.getElementsByTagName("pes");
  //partialArray = xmlRoot.getElementsByTagName("partial");
  numArray = xmlRoot.getElementsByTagName("num");
  priceArray = xmlRoot.getElementsByTagName("price");
  hiddenArray = xmlRoot.getElementsByTagName("id_hidden");
	
  // display
  var num_item = numArray.item(0).firstChild.data;
  if (num_item != 0){
	var prezzo = priceArray.item(0).firstChild.data;
	//var parziale = partialArray.item(0).firstChild.data;
	var totale = totalArray.item(0).firstChild.data;
	var peso = pesArray.item(0).firstChild.data;
	var idItem = hiddenArray.item(0).firstChild.data;
	var num = numArray.item(0).firstChild.data;
	var id_qty = 'ackinput_qty_' + idItem;
	var id_qty_hidden = 'qty_hidden_' + idItem;
	var id_prezzo = 'price_' + idItem;
	var idRow = 'row_' + idItem;
	
	document.getElementById("totale").innerHTML = totale + ' €';
	document.getElementById("peso").innerHTML = peso;
	//document.getElementById("parziale").innerHTML = '€' + parziale;
	document.getElementById(id_qty).value = num;
	document.getElementById(id_qty_hidden).value = num;
	document.getElementById(id_prezzo).innerHTML = prezzo + ' €';

	//fadeup(idRow,255,126,153);
	// ERA: if (num_item > 1){
	/*if (num_item > 0){
		set_shipment();
	}*/

  }
  document.body.style.cursor = 'auto';
}

// handles the response received from the server
function handleServerResponse_ship_pay()
{
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;
  //catturo errori con IE e opera
  if (!xmlResponse || !xmlResponse.documentElement){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  //catturo gli errori con Firefox
  var rootNodeName = xmlResponse.documentElement.nodeName;
  if (rootNodeName == "parsererror"){
	  throw("Struttura XML non valida:\n" + xmlHttp.responseText);
  }
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;  
  totalArray = xmlRoot.getElementsByTagName("total");
  //shipmentArray = xmlRoot.getElementsByTagName("shipment");
  //paymentArray = xmlRoot.getElementsByTagName("payment");
	
  // display
  var totale = totalArray.item(0).firstChild.data;
  //alert('totale ' + totale);
  //var spedizione = shipmentArray.item(0).firstChild.data;
  //var pagamento = paymentArray.item(0).firstChild.data;

  document.getElementById("totale").innerHTML = '€' + totale;
  //document.getElementById("ship_cost").innerHTML = '€' + spedizione;
  //document.getElementById("pay_cost").innerHTML = '€' + pagamento;

  document.body.style.cursor = 'auto';
}