/** (C) HTML.IT - insieme di funzioni ed oggetti utili per interagire con ajax */

/** FUNZIONI */

	// funzione per prendere un elemento con id univoco
		function prendiElementoDaId(id_elemento) 
    {
			var elemento;
			if(document.getElementById)
				elemento = document.getElementById(id_elemento);
			else
				elemento = document.all[id_elemento];
			return elemento;
		};
	
	// funzione per assegnare un oggetto XMLHttpRequest
		function assegnaXMLHttpRequest() 
    {
			var
			XHR = null,
			browserUtente = navigator.userAgent.toUpperCase();
			if(typeof(XMLHttpRequest) === "function" || typeof(XMLHttpRequest) === "object")
				XHR = new XMLHttpRequest();
			else if(window.ActiveXObject && browserUtente.indexOf("MSIE 4") < 0) 
      {
				if(browserUtente.indexOf("MSIE 5") < 0)
				{
					XHR = new ActiveXObject("Msxml2.XMLHTTP");
					//alert('IE vecchio');
				}
				else
				{
					XHR = new ActiveXObject("Microsoft.XMLHTTP");
					//alert('IE nuovo');
				}
			}
			return XHR;
		};



/** OGGETTI / ARRAY */

	// oggetto di verifica stato
		var readyState = 
    {
			INATTIVO:	0,
			INIZIALIZZATO:	1,
			RICHIESTA:	2,
			RISPOSTA:	3,
			COMPLETATO:	4
		};

	// array descrittivo dei codici restituiti dal server
	// [la scelta dell' array è per evitare problemi con vecchi browsers]
		var statusText = new Array();
		statusText[100] = "Continue";
		statusText[101] = "Switching Protocols";
		statusText[200] = "OK";
		statusText[201] = "Created";
		statusText[202] = "Accepted";
		statusText[203] = "Non-Authoritative Information";
		statusText[204] = "No Content";
		statusText[205] = "Reset Content";
		statusText[206] = "Partial Content";
		statusText[300] = "Multiple Choices";
		statusText[301] = "Moved Permanently";
		statusText[302] = "Found";
		statusText[303] = "See Other";
		statusText[304] = "Not Modified";
		statusText[305] = "Use Proxy";
		statusText[306] = "(unused, but reserved)";
		statusText[307] = "Temporary Redirect";
		statusText[400] = "Bad Request";
		statusText[401] = "Unauthorized";
		statusText[402] = "Payment Required";
		statusText[403] = "Forbidden";
		statusText[404] = "Not Found";
		statusText[405] = "Method Not Allowed";
		statusText[406] = "Not Acceptable";
		statusText[407] = "Proxy Authentication Required";
		statusText[408] = "Request Timeout";
		statusText[409] = "Conflict";
		statusText[410] = "Gone";
		statusText[411] = "Length Required";
		statusText[412] = "Precondition Failed";
		statusText[413] = "Request Entity Too Large";
		statusText[414] = "Request-URI Too Long";
		statusText[415] = "Unsupported Media Type";
		statusText[416] = "Requested Range Not Satisfiable";
		statusText[417] = "Expectation Failed";
		statusText[500] = "Internal Server Error";
		statusText[501] = "Not Implemented";
		statusText[502] = "Bad Gateway";
		statusText[503] = "Service Unavailable";
		statusText[504] = "Gateway Timeout";
		statusText[505] = "HTTP Version Not Supported";
		statusText[509] = "Bandwidth Limit Exceeded";
		
function getFormValue()
{
    car = document.carrello.carrello.value;
    cod_art = document.carrello.cod_art.value; 
    qta = document.carrello.qta.value; 
    id = document.carrello.id.value; 
    id_cat = document.carrello.id_cat.value; 
    prez = document.carrello.prezzo.value;
    
    postVars = "carrello="+car+"&cod_art="+cod_art+"&qta="+qta+"&id="+id+"&id_cat="+id_cat+"&prezzo="+prez;
    
    if(document.carrello.taglia)
    {
        taglia = document.carrello.taglia.value;
        postVars += "&taglia="+taglia;
    } 
    if(document.carrello.id_colore)
    {
        id_colore = document.carrello.id_colore.value;
        postVars += "&id_colore="+id_colore;
    }
    
    return postVars; 
}


function aggiungiArticolo() 
{
  // variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest(),
    // assegnazione elementi del documento
    elemento = prendiElementoDaId("tab-aggiunto");
    n_pezzi = prendiElementoDaId("text-carrello");
    ico = prendiElementoDaId("ico-carrello");
  
  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) 
  {
      postVars = getFormValue();
      //alert(postVars);
      // inizializzo la richiesta in post
      ajax.open("post", "addCarrello.php", true);
    
      // imposto il giusto header
      ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");

      // rimozione dell'header "connection" come "keep alive"
      ajax.setRequestHeader("connection", "close");

      // impostazione controllo e stato della richiesta
      ajax.onreadystatechange = function() 
      {
          // verifica dello stato
          if(ajax.readyState === readyState.COMPLETATO) 
          {
              // verifica della risposta da parte del server
              if(statusText[ajax.status] === "OK")
              {
                  resp = ajax.responseText.split('@');                
                  elemento.innerHTML = resp[2];
                  elemento.style.visibility='visible';
                  n_pezzi.innerHTML = resp[1]+" prodotti nel carrello";
                  ico.innerHTML = resp[0];
                  document.carrello.qta.value = '';
              }
              else if(ajax.status == "12030")
              {
                  //alert("ERROR_INTERNET_CONNECTION_ABORTED");
                  aggiungiArticolo();
              }
              else  
              {
                  // errore di caricamento
                  elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
                  elemento.innerHTML += "Errore riscontrato: " + ajax.status;
                  elemento.style.visibility='visible';
                  /*alert("Errore connessione asincrona");
                  resp = ajax.responseText.split('@');                
                  elemento.innerHTML = resp[2];
                  elemento.style.visibility='visible';
                  n_pezzi.innerHTML = resp[1]+" prodotti nel carrello";
                  ico.innerHTML = resp[0];
                  document.carrello.qta.value = '';*/
              }
          } 
      }
      // effettuo la richiesta inviando le variabili 
      ajax.send(postVars); 
  }
}

function aggiornaTotali(tot) 
{
    totali = prendiElementoDaId("text-carrello");
    totali.innerHTML = tot+" prodotti nel carrello";
}

function photoSwitch(path_new, path_actual) 
{
  // variabili di funzione
  var
    // assegnazione oggetto XMLHttpRequest
    ajax = assegnaXMLHttpRequest(),
    // assegnazione elementi del documento
    foto = prendiElementoDaId("fotoID");
    tst = prendiElementoDaId("tasto");
  
  // se l'oggetto XMLHttpRequest non è nullo
  if(ajax) 
  {
      postVars = "path_new="+path_new+"&path_actual="+path_actual;
      //alert(postVars);
      // inizializzo la richiesta in post
      ajax.open("post", "photoSwitch.php", true);
    
      // imposto il giusto header
      ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");

      // rimozione dell'header "connection" come "keep alive"
      ajax.setRequestHeader("connection", "close");

      // impostazione controllo e stato della richiesta
      ajax.onreadystatechange = function() 
      {
          // verifica dello stato
          if(ajax.readyState === readyState.COMPLETATO) 
          {
              // verifica della risposta da parte del server
              if(statusText[ajax.status] === "OK")
              {               
                  resp = ajax.responseText.split('@');                
                  foto.innerHTML = resp[0];
                  tst.innerHTML = resp[1];
              }
              else 
              {
                  // errore di caricamento
                  elemento.innerHTML = "Impossibile effettuare l'operazione richiesta.<br />";
                  elemento.innerHTML += "Errore riscontrato: " + statusText[ajax.status];
                  elemento.style.visibility='visible';
              }
          } 
      }
      // effettuo la richiesta inviando le variabili 
      ajax.send(postVars); 
  }
}

function foto(img1, img2)
{
    //alert("PIPPO !!!");
    options=
    {
			loop: true,
			overlayOpacity: 0.4,
			overlayFadeDuration: 400,
			resizeDuration: 500,
			counterText: "Foto <strong>{x}</strong> di <strong>{y}</strong>",
			previousKeys: [37, 80, 16],
			nextKeys: [39, 78, 17]
		};
    
    if(img2 != "")
      Slimbox.open([[img1], [img2]], 0, options);
    else
      Slimbox.open([[img1]], 0, options);  
}

function controlla()
{
     continua = prendiElementoDaId("conferma");
     tasto = prendiElementoDaId("accetta");
     //alert(tasto.checked);
     if(tasto.checked)
        continua.style.visibility = 'visible';
     else
        continua.style.visibility = 'hidden';
}

function getCheckedValue(radioObj) 
{
	if(!radioObj)
		return false;
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return false;
	for(var i = 0; i < radioLength; i++) 
  {
	   if(radioObj[i].checked) 
     {
		    return radioObj[i].value;
		 }
	}
	return false;
}


function controlla_chiudi()
{
     tasto = prendiElementoDaId("tasto-chiudi");
     pagamento = document.conferma.pagamento;
     consegna = document.conferma.consegna;
     //alert(pagamento);
     if(getCheckedValue(pagamento) && getCheckedValue(consegna))
        tasto.style.visibility = 'visible';
     else
        tasto.style.visibility = 'hidden';
}

// decrypt helper function
function decryptCharcode(n,start,end,offset) 
{
  	n = n + offset;
  	if (offset > 0 && n > end)	
    {
  		n = start + (n - end - 1);
  	} 
    else if (offset < 0 && n < start)	
    {
  		n = end - (start - n - 1);
  	}
  	return String.fromCharCode(n);
}
// decrypt string
function decryptString(enc,offset) 
{
  	var dec = "";
  	var len = enc.length;
  	for(var i=0; i < len; i++)	
    {
  		var n = enc.charCodeAt(i);
  		if (n >= 0x2B && n <= 0x3A)	
      {
  			dec += decryptCharcode(n,0x2B,0x3A,offset);	// 0-9 . , - + / :
  			//alert('n vale:'+ n +'0-9');
  		} 
      else if (n >= 0x40 && n <= 0x5A)	
      {
  			dec += decryptCharcode(n,0x40,0x5A,offset);	// A-Z @
  			//alert('n vale:'+ n +'A-Z @');
  		} 
      else if (n >= 0x61 && n <= 0x7A)	
      {
  			dec += decryptCharcode(n,0x61,0x7A,offset);	// a-z
  			//alert('n vale:'+ n +'a-z');
  		} 
      else 
      {
  			dec += enc.charAt(i);
  		}
  	}
  	return dec;
}
  // decrypt spam-protected emails
function linkTo_UnCryptMailto(s)	{
	location.href = decryptString(s,-2);
}


