/*
	File: 	banner.js
	Creato:	il 18/12/2007	
*/

//	Global variables

var period 				= 0;										// the global interval period to refresh the banners
var minimumPeriod = 10000;								// minimal allowed interval period
var defaultPeriod	= 45000;								// the default interval period
var requestTarget = "/banner/banner.xml";	// target of the GET method
var globDom;															// The DOM object
var bannerDir	= "banner/";								// the repository for banners
var impressions ;										// how many times has been loaded a banner from start

/*
	----------------------------------------------------------------------------------------------
	La variabile che conferma il corretto parsing del file XML è true?
	Se no creo un flag nascosto da qualche parte per dare un warning, non faccio altro ed esco
	Altrimenti impegno l'evento bodyOnLoad temporizzandolo
	----------------------------------------------------------------------------------------------
*/

//	Prelevo il file xml di cui il metodo jquery fa direttamente il parsing

$.get(requestTarget, {}, saveXML);	// Metodo asincrono! Non so quando il parsing è completo!
dataSetup();												// start checking if data i available

/* 
	----------------------------------------------------------------------------------------------
 	check timely if the xml parsing has been completed successfully returning an object
	If so, start the fireBanner function
 	If not repeat
	----------------------------------------------------------------------------------------------
*/
	
function dataSetup()
{
	if (globDom) {
		fireBanner();
	}
	else
	{
		setTimeout("dataSetup()", 100);
	}
}

/* 
	----------------------------------------------------------------------------------------------
 	writes a text in the id provided as first argument
	Returns true if the element has been found, false otherwise
	----------------------------------------------------------------------------------------------
*/

function writeText(dstId, message){
	var dst;
	dst = document.getElementById("xml");
	if (dst){
   	dst.innerHTML = message;
   	return true;
  }
  return false;
}

/* 
	----------------------------------------------------------------------------------------------
 	writes a text in the id provided as first argument
	Returns true if the element has been found, false otherwise
	----------------------------------------------------------------------------------------------
*/

function appendText(dstId, message){
	var dst;
	dst = document.getElementById("xml");
	if (dst){
   	dst.innerHTML = dst.innerHTML + message;
   	return true;
  }
  return false;
}

/* 
	----------------------------------------------------------------------------------------------
 	La funzione è quella che materialmente attiva i banners
 	Non può nemmeno venire lanciata se l'oggetto xml non è correttamente analizzato
 	e presente nella variabile globale.
	----------------------------------------------------------------------------------------------
*/
function fireBanner(){
	var posizioni;												// banner position nodes;
	var posizione;												// banner position scalar value
	var j;																// loop variable
	var label;														// the html banner id
	var collegamenti;											// link nodes
	var linkTarget;												// link related to the banner image
	var ImageUrl;													// url 
	var bannerno;													// how many banners are within a place
	var k;																// image selector within a banner position
	
	if (period < 1)	{
		impressions = 0;												// first execution set impressions to 0
		period = setGlobalPeriod();						// if no previous parsing set the period
		setInterval("fireBanner()", period);	// fire event
	} 
	else
	{
		impressions++;												// increment impressions so far; 
	}
	
/* 
	per ogni posizione: determino se esiste una immagine da rendere;
	ottengo gli id dei contenitori per posizione;
	inserisco immagine e link
*/

	posizioni = globDom.getElementsByTagName("banner");	// get all banners
	for (j=0; j < posizioni.length; j++)								// per tutte le posizioni estraggo le informazioni 
	{
		posizione 		= posizioni[j].getAttribute("posizione");	// get the banner position
		label					= "banner" + parseInt(j + 1);							// build the banner id
		var dstBanner = document.getElementById(label);					// get the destination placeholder
		if (! dstBanner) {continue;}														// dst not found, banner placeholder not provided
		if (! posizioni[j].hasChildNodes()) {continue;}					// the  banner element has not link nodes
		
		collegamenti = posizioni[j].getElementsByTagName("link");	// get the link nodes
		bannerno = collegamenti.length;														// how many banners we have to deal with
		if (bannerno < 1) {continue;}															// No banners to be shown. Continue

/*
	Determine what is the right banner to be displayed based on the impressions and the number of the
	banners related to the position
*/		
			k = impressions % bannerno;
			
//		appendText("xml", "posizione: " + tmp + " " + label + "<br>");
// per tutte i nodi figlio cerco il nodo link appropriato		
		
			imageUrl = bannerDir + collegamenti[k].getAttribute("image");
			imageUrl = "<img class='banner' src='" + imageUrl  + "'>"
			linkTarget = nodeContent(collegamenti[k]);
//
// Qui manca la parte per la identificazione di quanto correntemente visualizzato e la selezione di 
//	quanto da visualizzare in una eventuale lista
// 				
			if (linkTarget.length > 0)
			{
				dstBanner.innerHTML = "<a href='" + linkTarget + "' target='_anewin' alt=ban>" + imageUrl + "</a>";
			}
			else
			{
				dstBanner.innerHTML = imageUrl ;
			}
	}
}

/* 
	----------------------------------------------------------------------------------------------
 	Setup the global refresh time from the XML or from default if unable to parse
	----------------------------------------------------------------------------------------------
*/
	
function setGlobalPeriod()
{
	var unableToParse	= false;																	// If true no parsing was possible
	var secondiNode	= 0;																				// local temporary variable to hold second node
	var nsec = 0;																								// local temporary variable to hold seconds
	
  secondiNode	 = globDom.getElementsByTagName("secondi")[0];	// get the time period from the xml if possible
	if (secondiNode)																						//  if element has been found 
	{
		nsec = parseInt(nodeContent(secondiNode));							// so set default
		if (isNaN(nsec)) {
			unableToParse	= true;													// something went wrong
		}
		else
		{
			nsec *= 1000;																	// transform in msec.
		}					
	}													
	else
	{
		unableToParse	= true;														//  no element found
	}									
	if (unableToParse)
	{
		return defaultPeriod;	// so set default										//  no element found
	}
	else
	{
		return nsec;	// so set default										//  no element found
	}
}

/* 
	----------------------------------------------------------------------------------------------
 	returns the text value of the node if found
	----------------------------------------------------------------------------------------------
*/
	
function nodeContent(nodo)
{
	if (! nodo) 								{return "";}		//  no element found
	if (! nodo.hasChildNodes()) {return "";}		//  no element found
	return nodo.lastChild.data;									//  node element value
}
	
/*
	----------------------------------------------------------------------------------------------
	La funzione copia il DOM XML corrispondente a quanto caricato dall'utente in una variabile
	globalmente accessibile.
	----------------------------------------------------------------------------------------------
*/

function saveXML(xmlDom)
{
	globDom = xmlDom;
}

/*
	----------------------------------------------------------------------------------------------
	The function transform a xml subtree in a string
	----------------------------------------------------------------------------------------------
*/	
function xml2Str(xmlNode)
{
  try {
    // Gecko-based browsers, Safari, Opera.
    return (new XMLSerializer()).serializeToString(xmlNode);
  }
  catch (e) {
    try {
      // Internet Explorer.
      return xmlNode.xml;
    }
    catch (e)
    {//Strange Browser ??
     alert('Xmlserializer not supported');
    }
  }
  return false;
}

/*
	----------------------------------------------------------------------------------------------
	Multiple onload function created by: Simon Willison
	http://simon.incutio.com/archive/2004/05/26/addLoadEvent
	Function is unused in this application
	----------------------------------------------------------------------------------------------
*/	

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

