/**
 *@fileoverview Simple example that shows how to encapsulate
 *XMLHTTPRequestCalls
 *
 *@author Mike Chambers (mesh@adobe.com)
 */

/**
 *Constructor for the class.
 *
 *@param {String} dataURL The path to the data that the class
 *will load (OPTIONAL)
 *
 *@constructor
 */
function blocco(divId, numeroRisultati)
{
    if(divId != undefined)
	{
	    this._divId = divId;
	    dataURL = '/div-struttura/'+divId+'.div.html';
	    this._dataURL = dataURL;
	}

    if(numeroRisultati != undefined)
	{
	    this._numeroRisultati = numeroRisultati;
	}

	/*    this._writeContainer();*/
}

blocco.prototype._divId = "contenuto";

blocco.prototype._numeroRisultati = "";

blocco.prototype._pagina = "0";
blocco.prototype._posizione = "0";

//where to load the data from
blocco.prototype._dataURL = "data.txt";

//var to hold an instance of the XMLHTTPRequest object
blocco.prototype._request = undefined;


//name of the css class for the HTML container
blocco.prototype._containerClass = "ml_container";

blocco.prototype.sql = "";

/**************** Public APIs **********************/

/**
 *Tells the class to load its data and render the results.
 */
blocco.prototype.load = function()
{
    //get a new XMLHTTPRequest and store it in an instance var.
    this._request = this._getXMLHTTPRequest();

    //set the var so we can scope the callback
    var _this = this;

    //callback will be an anonymous function that calls back into our class
    //this allows the call back in which we handle the response (_onData())
    // to have the correct scope.
    this._request.onreadystatechange = function(){_this._onData()};
    totaleRecord = parseInt(this._numeroRisultati) + 1;
    qrystr="sqlxml.inc.php?sql="+this.sql+" LIMIT "+this._posizione+","+totaleRecord+"&ts="+new Date().getTime();
    this._request.open("POST", qrystr, true);
    this._request.send(null);
}

blocco.prototype.inviaSql = function(sql)
{	    
    //get a new XMLHTTPRequest and store it in an instance var.
    this._request = this._getXMLHTTPRequest();
    
    //set the var so we can scope the callback
    var _this = this;
    this.sql=sql;
    
    //callback will be an anonymous function that calls back into our class
    //this allows the call back in which we handle the response (_onData())
    // to have the correct scope.
    this._request.onreadystatechange = function(){_this._onData()};
    totaleRecord = parseInt(this._numeroRisultati) + 1;
    qrystr="sqlxml.inc.php?sql="+sql+" LIMIT "+this._posizione+","+totaleRecord+"&ts="+new Date().getTime();
    //    alert(qrystr);
    this._request.open("POST", qrystr, true);
    this._request.send(null);

    var regexp = new RegExp("INSERT INTO .+;","g");
    this.sql = this.sql.replace(regexp,'');
    var regexp = new RegExp("DELETE FROM .+;","g");
    this.sql = this.sql.replace(regexp,'');
    var regexp = new RegExp("UPDATE .+;","g");
    this.sql = this.sql.replace(regexp,'');
}

blocco.prototype.eseguiSql = function(sql)
{	    
    //get a new XMLHTTPRequest and store it in an instance var.
    this._request = this._getXMLHTTPRequest();
    
    //set the var so we can scope the callback
    var _this = this;
    this.sql=sql;
    
    //callback will be an anonymous function that calls back into our class
    //this allows the call back in which we handle the response (_onData())
    // to have the correct scope.
    this._request.onreadystatechange = function(){};
    qrystr="sqlxml.inc.php?sql="+sql+"&ts="+new Date().getTime();
    this._request.open("POST", qrystr, true);
    this._request.send(null);
}

blocco.prototype.avanti = function()
      {
	this._pagina++;
	this._posizione = parseInt(this._posizione) + this._numeroRisultati;
	this.inviaSql(this.sql);
      }
    
blocco.prototype.indietro = function()
      {
	this._pagina--;
	this._pagina = Math.max(0,this._pagina);
	this._posizione = parseInt(this._posizione) - this._numeroRisultati;
	this._posizione = Math.max(0,this._posizione);
	this.inviaSql(this.sql);
      }
    
/***************Private Rendering APIs ********************/

//writes the top level div for the class / widget
blocco.prototype._writeContainer = function()
{
    //styles should be in external CSS
    //    document.write("<div id='"+this._divId+"' class='"+this._containerClass+"'></div>");
}

//renders the entire widget
blocco.prototype._render = function(contenuto)
{
    /*    var content = document.getElementById(this._divId);
    content.appendChild(document.createTextNode(title));
    */
    var Records = contenuto.getElementsByTagName("record");
    var buf = caricaHtml('div-struttura/'+this._divId+'.div.html?timestamp='+new Date().getTime());
    for(var i = 0; i < Records.length; i++) 
    {
	prodotto = Records[i];
	//	for(var n = 0; n < prodotto.childNodes.length; n++) 
	for(var n = prodotto.childNodes.length-1; n>=0 ; n--) 
	    {
		if (prodotto.childNodes[n].firstChild)
		    {
			variabile = prodotto.childNodes[n].nodeName+i;
			valore = prodotto.childNodes[n].firstChild.nodeValue;
			//		  alert(variabile+' -> '+valore);
			var regexp = new RegExp("__"+variabile,"g");
			buf = buf.replace(regexp,valore);
		    }
	    }
    }
    //    alert(this._divId);
    //    alert(buf);
    document.getElementById(this._divId).innerHTML = buf;
}

/***************Private Data Loading Handlers*******************/

//return the URL from which the data will be loaded
blocco.prototype._generateDataUrl = function()
{
    return this._dataURL;
}

//callback for when the data is loaded from the server
blocco.prototype._onData = function()
{
    if(this._request.readyState == 4)
    {
	if(this._request.status == "200")
	{
	    this._render(this._request.responseXML);

	    //if the onDraw callback has been defined
	    //call it to let the listener know
	    //that we are done creating the list
	    if(this.onDraw != undefined)
	    {
		this.onDraw();
	    }
	}
	else
	{
	    //check if an error callback handler has been defined
	    if(this.onError != undefined)
	    {
		//pass an object to the callback handler with info
		//about the error
		this.onError({status:this_request.status,
					 statusText:this._request.statusText});
	    }
	}

	//clean up
	delete this._request;
    }
}

/***************Private Data Util Functions ********************/

//returns an XMLHTTPRequest instance (based on browser)
blocco.prototype._getXMLHTTPRequest = function()
{
    var xmlHttp;
    try
    {
	xmlHttp = new ActiveXObject("Msxml2.XMLHttp");
    }
    catch(e)
    {
	try
	{
	    xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
	}
	catch(e2)
	{
	}
    }

    if(xmlHttp == undefined && (typeof XMLHttpRequest != 'undefined'))
    {
	xmlHttp = new XMLHttpRequest();
    }

    return xmlHttp;
}


function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 

function visualizzaSchedaProdotto(codice, complementarieta, ba )
{
  function ricaricaSchedaProdotto(obj)
    {
      document.getElementById('offerte').innerHTML = '<div> </div>';
      document.getElementById('elencoProdotti').innerHTML = '<div> </div>';
      document.getElementById('schedaUtente').innerHTML = '<div> </div>';
      document.getElementById('contenutoSchedaProdotto').style.display='none';
      Prodotto.inviaSql('SELECT * FROM Prodotti WHERE codice = \'' + codice + '\'');
      ProdottiCorrelati.inviaSql('SELECT * FROM Prodotti WHERE Prodotti.visibilita NOT LIKE \'no\' AND complementarieta NOT LIKE \'\' AND complementarieta = \''+complementarieta+'\' AND codice NOT LIKE \''+codice+'\'');
      document.getElementById('navigazione').innerHTML = caricaHtml('navigazione/'+ba+'_nav.div.html')+' > Scheda Prodotto';
      //      document.getElementById('indice').innerHTML = 'SELECT * FROM Prodotti WHERE Prodotti.visibilita NOT LIKE \'no\' AND complementarieta NOT LIKE \'\' AND complementarieta = \''+complementarieta+'\' AND codice NOT LIKE \''+codice+'\'';
      new Effect.Appear('contenutoSchedaProdotto', {duration: 2});
    }
  
  if (document.getElementById('elencoProdotti').innerHTML == '<div> </div>')
      {
	  new Effect.Fade('contenutoSchedaProdotto',{duration: 2, afterFinish: ricaricaSchedaProdotto});
      } 
  else 
      {
	  new Effect.Fade('elencoProdotti',{duration: 2, afterFinish: ricaricaSchedaProdotto});
      }
}
function visualizzaSchedaProdottoDaBA(codice, complementarietaBA)
{
  function ricaricaSchedaProdotto(obj)
    {
      document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
      Prodotto.inviaSql('SELECT * FROM Prodotti WHERE codice = \'' + codice + '\'');
      ProdottiCorrelati.inviaSql('SELECT * FROM Prodotti WHERE Prodotti.visibilita NOT LIKE \'no\' AND complementarietaBA NOT LIKE \'\' AND complementarietaBA = \''+complementarietaBA+'\' AND codice NOT LIKE \''+codice+'\'');
      Carrello.load();
      RiassuntoCarrello.load();
      new Effect.Appear('contenuto', {duration: 2});
    }
  
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaSchedaProdotto});

}

function caricaContenutoIndice(contenuto)
{    
  function ricaricaContenutoIndice(obj)
  {
      document.getElementById('contenuto').style.display='none';
      document.getElementById('contenuto').innerHTML = caricaHtml(contenuto);
      //   document.getElementById('navigazione').innerHTML = contenuto;
      new Effect.Appear('contenuto', {duration: 4});
  }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoIndice});
}

function caricaContenutoMartina(contenuto)
{    
  function ricaricaContenutoMartina(obj)
  {
      document.getElementById('contenuto').style.display='none';
      document.getElementById('contenuto').innerHTML = caricaHtml(contenuto);
      //   document.getElementById('navigazione').innerHTML = contenuto;
      new Effect.Appear('contenuto', {duration: 4});
  }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoMartina});
}

function attivaCatalogo(famiglia, navigazione)
{    
  function ricaricaContenutoCatalogo(obj)
  {
  document.getElementById('contenuto').style.display='none';
  document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
  Prodotti.pagina=0; Prodotti.posizione=0;
  Prodotti.inviaSql('SELECT * FROM Prodotti WHERE Prodotti.visibilita NOT LIKE \'no\' AND famiglia LIKE \''+famiglia+'\' ORDER BY priorita ASC');
  //document.getElementById('navigazione').innerHTML = navigazione;
  document.getElementById('navigazione').innerHTML = caricaHtml('navigazione/'+famiglia+'_nav.div.html');
  Carrello.load();
  RiassuntoCarrello.load();
  new Effect.Appear('contenuto', {duration: 4});
   }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoCatalogo});
  //  document.getElementById('contenuto').style.display='block';
    
}

function registraUtente(email, pass)
{
  function ricaricaContenutoCatalogo(obj)
  {
      document.getElementById('contenuto').style.display='none';
      document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
      Utente.inviaSql('INSERT INTO Utenti (email, pass) VALUES (\''+ email + '\', \'' + pass + '\'); SELECT * FROM Utenti WHERE email = \'' + email + '\' AND pass = \'' + document.getElementById('pass').value + '\'');
      document.getElementById('navigazione').innerHTML = 'Scheda Utente';
      Carrello.load();
      RiassuntoCarrello.load();
      new Effect.Appear('contenuto', {duration: 4});
  }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoCatalogo});
}

function attivaSchedaUtente()
{    
  function ricaricaContenutoCatalogo(obj)
  {
      document.getElementById('contenuto').style.display='none';
      document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
      Utente.inviaSql('SELECT * FROM Utenti WHERE email = \''+ document.getElementById('email').value + '\' AND pass = \'' + document.getElementById('pass').value + '\'');
      //      document.getElementById('schedaUtente').innerHTML = caricaHtml('div-struttura/schedaUtente.div.html');
      document.getElementById('navigazione').innerHTML = 'Scheda Utente';
      Carrello.load();
      RiassuntoCarrello.load();
      new Effect.Appear('contenuto', {duration: 4});
  }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoCatalogo});
  //  document.getElementById('contenuto').style.display='block';
    
}

function attivaProcediConLordine()
{    
  function ricaricaContenutoCatalogo(obj)
  {
      document.getElementById('contenuto').style.display='none';
      document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
      procediConLordine.inviaSql('SELECT * FROM Utenti WHERE email = \''+ document.getElementById('email').value + '\' AND pass = \'' + document.getElementById('pass').value + '\'');
      //      document.getElementById('schedaUtente').innerHTML = caricaHtml('div-struttura/schedaUtente.div.html');
      document.getElementById('navigazione').innerHTML = 'Dati di fatturazione e di spedizione';
      Carrello.load();
      RiassuntoCarrello.load();
      new Effect.Appear('contenuto', {duration: 4});
  }
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoCatalogo});
  //  document.getElementById('contenuto').style.display='block';
    
}

function aggiornaUtente()
{
    if(performCheck('cassa', rules, 'classic'))
    {
    pi=''; pa=''; pm=''; pp='';
    if (document.getElementById('privacyInformativa') != null)
	{
	    if (document.getElementById('privacyInformativa').checked) {pi='checked'};
	    if (document.getElementById('privacyAcquisto').checked) {pa='checked'};
	    if (document.getElementById('privacyMarketing').checked) {pm='checked'};
	    if (document.getElementById('privacyProfilazione').checked) {pp='checked'};
	}
    Utente.eseguiSql(
   'UPDATE Utenti SET nome = \'' + document.getElementById('nome').value + '\'' +
   ', cognome = \'' + document.getElementById('cognome').value + '\'' +
   ', societa = \'' + document.getElementById('societa').value + '\'' +
   ', indirizzo = \'' + document.getElementById('indirizzo').value + '\'' +
    ', cap = \'' + document.getElementById('cap').value + '\'' +
   ', citta = \'' + document.getElementById('citta').value + '\'' +
   ', provincia = \'' + document.getElementById('provincia').value + '\'' +
   ', nazione = \'' + document.getElementById('nazione').value + '\'' +
   ', telefono = \'' + document.getElementById('telefono').value + '\'' +
   ', cellulare = \'' + document.getElementById('cellulare').value + '\'' +
   ', codiceFiscale = \'' + document.getElementById('codiceFiscale').value + '\'' +
   ', tramiteSpedizione = \'' + document.getElementById('tramiteSpedizione').value + '\'' +
   ', momentoSpedizione = \'' + document.getElementById('momentoSpedizione').value + '\'' +
   ', mezzoPagamento = \'' + document.getElementById('mezzoPagamento').value + '\'' +
   ', privacyInformativa = \'' + pi  + '\'' +
   ', privacyAcquisto = \'' + pa + '\'' +
   ', privacyMarketing = \'' + pm + '\'' +
   ', privacyProfilazione = \'' + pp + '\'' +
   ' WHERE email = \''+document.getElementById('email').value+'\''+
   '; SELECT * FROM Utenti WHERE email = \'' + document.getElementById('email').value + '\' AND pass = \'' + document.getElementById('pass').value + '\''
       );

   if (document.getElementById('nazione').value!='Italia')
       {
	   spedizione=25;
       }
   else 
       {
	   spedizione=10;
	   }

   
   RiassuntoCarrello.inviaSql('SELECT sum(Prodotti.prezzoFinale*Carrello.quantita) as totaleProdotti, sum(Prodotti.prezzoFinale*Carrello.quantita)%2B'+spedizione+'%2B'+paccoRegalo+' as totale,'+spedizione+' as spedizione,'+paccoRegalo+' as paccoRegalo FROM Prodotti, Carrello WHERE Prodotti.codice = Carrello.codiceProdotto AND Carrello.sessione = \''+getCookie('sessione')+'\' GROUP BY Carrello.sessione');
    }
}

function aggiornaRegistrazione()
{
    aggiornaUtente();
    caricaHtml('invioEmail.php?email='+document.getElementById('email').value+'&pw='+document.getElementById('pass').value);
    alert('Benvenuto su AGORA-HOME, i tuoi dati sono stati registrati.');
}

function aggiornaPaccoRegalo()
{
   if (document.getElementById('paccoRegalo').checked)
       {
	   paccoRegalo=3; // Se non e' in promozione
	   paccoRegalo=0;

       }
   else 
       {
	   paccoRegalo=0;
       }
   
   RiassuntoCarrello.inviaSql('SELECT sum(Prodotti.prezzoFinale*Carrello.quantita) as totaleProdotti, sum(Prodotti.prezzoFinale*Carrello.quantita)%2B'+spedizione+'%2B'+paccoRegalo+' as totale,'+spedizione+' as spedizione,'+paccoRegalo+' as paccoRegalo FROM Prodotti, Carrello WHERE Prodotti.codice = Carrello.codiceProdotto AND Carrello.sessione = \''+getCookie('sessione')+'\' GROUP BY Carrello.sessione');

}

function attivaRicerca(testo)
{    
    if (testo.length>3)
	{
	    function ricaricaContenutoRicerca(obj)
		{
		    document.getElementById('contenuto').style.display='none';
		    document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
		    Prodotti.pagina=0; Prodotti.posizione=0;
		    Prodotti.inviaSql('SELECT * FROM Prodotti WHERE descrizioneBreve REGEXP \'' + testo + '\' OR codice REGEXP \'' + testo + '\' OR marca LIKE \''+testo+ '\' OR correlazione REGEXP \'' + testo+ '\' ORDER BY priorita DESC');
		    //  $('indice').innerHTML='SELECT * FROM Prodotti WHERE descrizioneBreve REGEXP \'' + testo + '\' OR codice LIKE \'%' + testo + '%\'';
		    document.getElementById('navigazione').innerHTML = 'Ricerca libera';
		    Carrello.load();
		    RiassuntoCarrello.load();
		    new Effect.Appear('contenuto', {duration: 2});
		}
	    new Effect.Fade('contenuto',{duration: 1, afterFinish: ricaricaContenutoRicerca});
	    //  document.getElementById('contenuto').style.display='block';
	}
}

function aggiungiProdotto(sessione, codice)
{
    Carrello.eseguiSql("INSERT INTO Carrello (codiceProdotto, quantita, sessione) VALUES ('" + codice + "', 1, '" + sessione + "')");
    Carrello.inviaSql('SELECT Carrello.id as id, Prodotti.descrizioneBreve as descrizioneBreve, Prodotti.prezzoFinale as prezzoFinale, sum(Prodotti.prezzoFinale*Carrello.quantita) as subTotale, sum(Carrello.quantita) as quantita, Prodotti.codice as codice FROM Prodotti, Carrello  WHERE Prodotti.codice = Carrello.codiceProdotto  AND Carrello.sessione = \''+sessione+'\' GROUP BY Prodotti.codice');
    RiassuntoCarrello.load();
}

function aggiornaQuantita(sessione, codice, quantita)
{
    Carrello.eseguiSql('DELETE FROM Carrello WHERE sessione = \'' + sessione + '\' AND codiceProdotto = \''+ codice +'\'');
    if (quantita != 0) Carrello.eseguiSql('INSERT INTO Carrello (codiceProdotto, quantita, sessione) VALUES (\'' + codice + '\',' + quantita + ', \'' + sessione + '\');');
    Carrello.inviaSql('SELECT Carrello.id as id, Prodotti.descrizioneBreve as descrizioneBreve, Prodotti.prezzoFinale as prezzoFinale, sum(Prodotti.prezzoFinale*Carrello.quantita) as subTotale, sum(Carrello.quantita) as quantita, Prodotti.codice as codice FROM Prodotti, Carrello  WHERE Prodotti.codice = Carrello.codiceProdotto  AND Carrello.sessione = \''+sessione+'\' GROUP BY Prodotti.codice');
    RiassuntoCarrello.load();
}

function visualizzaPromozioni()
{
    function ricaricaContenutoCatalogo(obj)
	{
	    document.getElementById('contenuto').style.display='none';
	    document.getElementById('contenuto').innerHTML = caricaHtml('div-struttura/contenutoCatalogo.div.html');
	    Prodotti.pagina=0; Prodotti.posizione=0;
	    Prodotti.inviaSql('SELECT * FROM Prodotti WHERE Prodotti.visibilita NOT LIKE \'no\' AND inPromozione LIKE \'si\' ORDER BY priorita ASC');
	    document.getElementById('offerte').innerHTML = caricaHtml('martina/offerte.div.html');
	    Carrello.load();
	    RiassuntoCarrello.load();
	    new Effect.Appear('contenuto', {duration: 4});
	}
  new Effect.Fade('contenuto',{duration: 2, afterFinish: ricaricaContenutoCatalogo});
  //  document.getElementById('contenuto').style.display='block';
  
}

function avviaPagamento() 
{
    var regexp = new RegExp(",","g");
    var totale = document.getElementById('totale').innerHTML.replace(regexp,'.');
    document.getElementById('b').value = totale * 32849172;
    //alert(totale*32849172);

    var sp='';
    if (document.getElementById('spedizioneAlternativa').checked) {sp='2';}

    if ((document.getElementById('mezzoPagamento').value != 'Carta di Credito'))
	{
	   document.getElementById('cassa').action='carrello.php'; 
	   document.getElementById('id').value=getCookie('sessione');
	}

   Ordine.eseguiSql(
     'INSERT INTO Ordini (email, sessioneCarrello, nome, cognome, societa, indirizzo, cap, citta, provincia, nazione, telefono, cellulare, codicefiscale, tramiteSpedizione, momentoSpedizione, mezzoPagamento, paccoRegalo, speseSpedizione) VALUES (\''+document.getElementById('email').value + '\', \'' +
     getCookie('sessione') + '\', \'' +
     document.getElementById('nome'+sp).value + '\', \'' +
     document.getElementById('cognome'+sp).value + '\', \'' +
     document.getElementById('societa'+sp).value + '\', \'' +
     document.getElementById('indirizzo'+sp).value + '\', \'' +
     document.getElementById('cap'+sp).value + '\', \'' +
     document.getElementById('citta'+sp).value + '\', \'' +
     document.getElementById('provincia'+sp).value + '\', \'' +
     document.getElementById('nazione'+sp).value + '\', \'' +
     document.getElementById('telefono'+sp).value + '\', \'' +
     document.getElementById('cellulare').value + '\', \'' +
     document.getElementById('codiceFiscale').value + '\', \'' +
     document.getElementById('tramiteSpedizione').value + '\', \'' +
     document.getElementById('momentoSpedizione').value + '\', \'' +
     document.getElementById('mezzoPagamento').value + '\', ' +
	   paccoRegalo+ ', '+spedizione+')');

   Ordine.eseguiSql('INSERT INTO CarrelliOrdinati SELECT * FROM Carrello WHERE sessione = \''+getCookie('sessione')+'\'');
}


function caricaHtml2(urlFrammento) 
{
var temp;
new Ajax.Request(urlFrammento,
  {
    method:'get',
    onSuccess: function(transport){
      temp = transport.responseText || "no response text";
    },
    onFailure: function(){ alert('Something went wrong...') }
  });
return temp;
}

function caricaHtml(urlFrammento) 
{
    var ml = new messageLoader(urlFrammento);
    ml.load();
    
    return ml._request.responseText;
}

/**
 *@fileoverview Simple example that shows how to encapsulate
 *XMLHTTPRequestCalls
 *
 *@author Mike Chambers (mesh@adobe.com)
 */

/**
 *Constructor for the class.
 *
 *@param {String} dataURL The path to the data that the class
 *will load (OPTIONAL)
 *
 *@constructor
 */
function messageLoader(dataURL)
{
    if(dataURL != undefined)
	{
	    this._dataURL = dataURL;
	}
}

//where to load the data from
messageLoader.prototype._dataURL = "data.txt";

//var to hold an instance of the XMLHTTPRequest object
messageLoader.prototype._request = undefined;

/**************** Public APIs **********************/

/**
 *Tells the class to load its data and render the results.
 */
messageLoader.prototype.load = function()
{
    //get a new XMLHTTPRequest and store it in an instance var.
    this._request = this._getXMLHTTPRequest();

    //set the var so we can scope the callback
    var _this = this;

    //callback will be an anonymous function that calls back into our class
    //this allows the call back in which we handle the response (_onData())
    // to have the correct scope.
    this._request.onreadystatechange = function(){_this._onData()};
    this._request.open("GET", this._generateDataUrl(), false);
    this._request.send(null);
}

/***************Private Rendering APIs ********************/

//renders the entire widget
messageLoader.prototype._render = function(title)
{
    var content = document.getElementById(this._containerID); 
//    content.appendChild(document.createTextNode(title));
    var temp = document.createTextNode(title);
//    alert(temp);
    content.appendChild(temp);
}

/***************Private Data Loading Handlers*******************/

//return the URL from which the data will be loaded
messageLoader.prototype._generateDataUrl = function()
{
    return this._dataURL;
}

//callback for when the data is loaded from the server
messageLoader.prototype._onData = function()
{
    if(this._request.readyState == 4)
    {
	if(this._request.status == "200")
	{
	    //	    this._render(this._request.responseText);
	    alert(this._render(this._request.responseText));
	    //if the onDraw callback has been defined
	    //call it to let the listener know
	    //that we are done creating the list
	    if(this.onDraw != undefined)
	    {
		this.onDraw();
	    }
	}
	else
	{
	    //check if an error callback handler has been defined
	    if(this.onError != undefined)
	    {
		//pass an object to the callback handler with info
		//about the error
		this.onError({status:this_request.status,
					 statusText:this._request.statusText});
	    }
	}

	//clean up
	delete this._request;
    }
}

/***************Private Data Util Functions ********************/

//returns an XMLHTTPRequest instance (based on browser)
messageLoader.prototype._getXMLHTTPRequest = function()
{
    var xmlHttp;
    try
    {
	xmlHttp = new ActiveXObject("Msxml2.XMLHttp");
    }
    catch(e)
    {
	try
	{
	    xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
	}
	catch(e2)
	{
	}
    }

    if(xmlHttp == undefined && (typeof XMLHttpRequest != 'undefined'))
    {
	xmlHttp = new XMLHttpRequest();
    }

    return xmlHttp;
}

// imposta il cookie sNome = sValore
// per la durata di iGiorni
function setCookie(sNome, sValore, iGiorni) {
    var dtOggi = new Date()
    var dtExpires = new Date()
  dtExpires.setTime
    (dtOggi.getTime() + 24 * iGiorni * 3600000)
    document.cookie = sNome + "=" + escape(sValore) +
    "; expires=" + dtExpires.toGMTString();
}

// restituisce il valore del cookie sNome
function getCookie(sNome) {
    // genera un array di coppie "Nome = Valore"
    // NOTA: i cookies sono separati da ';'
    var asCookies = document.cookie.split("; ");
    // ciclo su tutti i cookies
    for (var iCnt = 0; iCnt < asCookies.length; iCnt++)
	{
	    // leggo singolo cookie "Nome = Valore"
	    var asCookie = asCookies[iCnt].split("=");
	    if (sNome == asCookie[0]) { 
		return (unescape(asCookie[1]));
	    }
	}

    // SE non esiste il cookie richiesto
    return("");
}

// rimuove un cookie
function delCookie(sNome) {
    setCookie(sNome, "");
}

function rnd()
{
    rnd.seed = (rnd.seed*9301+49297) % 233280;
    return rnd.seed/(233280.0);
};

function rand(number)
{
    return Math.ceil(rnd()*number);
};

function loadjscssfile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
	var fileref=document.createElement('script')
	    fileref.setAttribute("type","text/javascript")
	    fileref.setAttribute("src", filename)
	    }
    else if (filetype=="css"){ //if filename is an external CSS file
	var fileref=document.createElement("link")
	    fileref.setAttribute("rel", "stylesheet")
	    fileref.setAttribute("type", "text/css")
	    fileref.setAttribute("href", filename)
	    }
    if (typeof fileref!="undefined")
	document.getElementsByTagName("head")[0].appendChild(fileref)
	    }

function toggleDisplay(me){
    if (document.getElementById(me).style.display=="block"){
	document.getElementById(me).style.display="inline";
    }
    else {
	if (document.getElementById(me).style.display=="inline"){
	    document.getElementById(me).style.display="none";
	}
	else {
	    document.getElementById(me).style.display="block";
	}
    }
}

function toggleVisibility(me){
    if (document.getElementById(me).style.visibility=="hidden"){
	document.getElementById(me).style.visibility="visible";
	}
    else {
	document.getElementById(me).style.visibility="hidden";
	}
    }

