/*
 +++++++++++++++++++++++++++++++++++++ Esempio di utilizzo dello scroller +++++++++++++++++++++++++++++++++++++
 
 All'interno della pagina in cui si vuole includere lo scroller vanno definiti questi elementi
	
		    <!-- 
		       div necessario per mantenere la fisso il riquadro dell'immagine.
		       Con il solo div "newsImage non potrei mantenere una dimensione costante
		       perche' distorcerei le proporzioni e le dimensioni delle immagini
		    -->
			<div id="divNewsImage" class="divNewsImage"> 	
				<img id="newsImage" class="newsImage">
			</div>
	
			<div id="rssNewsContainer"> </div>

All'interno della pagina stessa va richiamata la funzione GetRSS che effettua la chiamata Ajax per ottenere
il feed RSS delle news e inizializza lo scroller

<script type="text/javascript">
     
     // IMPORTANTE: GetRSS() necessita di prototype.js per effettuare la chiamata Ajax per ottenere le news 
     
      
     	GetRSS(newsContainerId, newsImageId, newsConfigId, newsViewTime, scrollingPixel, scrollingInterval)
        	newsContainerId = id del div che conterra' le news
         	newsImageIdid = id dell'elemento immagine che visualizzera' le immagini associate alle news
       	  Opzionali:
       	    newsConfigId = id della categoria di news richiesta (si veda file config.properties) 
         	newsViewTime = tempo di visualizzazione (quando e' finito lo scrolling)
         	               di una news (in millisecondi), per default 3000
         	scrollingPixel = pixel di shift per lo scrolling, per default 10
         	scrollingInterval = intervallo per il refresh dello scrolling (in millisecondi), per default 35
     
     
	 GetRSS("rssNewsContainer", "newsImage", null, 3000, 10, 35); 
	 
	 // GetRSS("rssNewsContainer", "newsImage", "news.config.id=.1", 3000, 10, 35); 
</script>

 Lo scroller inoltre necessita di un foglio di stile analogo al seguente:	
 
	#nodiItems {
		width: 300px;
		height: 150px;
		border: 1px solid black;
		padding: 5px;
		background-color: #F0F0F0;
	}
	
	.rssclass .rsstitle {
		font-weight: bold;
	}
	
	.rssclass .rssdate {
		color: gray;
		font-size: 85%;
	}
	
	.rssclass a {
		text-decoration: none;
	}
	
	.divNewsImage {
	    border:1px solid;
		height:100px;
		width:200px;
	}
	
	.newsImage {
	    display: none;
	}
*/

/*
======================================================================
Pausing RSS scroller JavaScript engine- © Dynamic Drive (http://www.dynamicdrive.com)
Docs: http://www.dynamicdrive.com/dynamicindex17/rsspausescroller/
Last modified: March 16th, 2006.
======================================================================
*/

// --------------------- variabili globali ---------------------

// contiene i dati delle news. Viene inizializzata al ritorno dalla chiamata Ajax dalla funzione ParseXMLFeed
/* 
  Tale variabile avrà un valore del genere:
	rsscontentdata.nodiItems[0]={link:"...", title:"...", description:"...", date:"...", media:"..."}
	rsscontentdata.nodiItems[1]={link:"...", title:"...", description:"...", date:"...", media:"..."}
	rsscontentdata.nodiItems[2]={link:"...", title:"...", description:"...", date:"...", media:"..."}
*/
var rsscontentdata = new Array();
rsscontentdata.nodiItems = new Array();

// id del div che contiene le news
var newsContainer;

// id dell'elemento immagine che visualizzera' le immagini associate alle news
var newsImage;

// tempo di visualizzazione (quando e' finito lo scrolling) di una news (in millisecondi)
var newsViewTime = 3000; // default

// pixel di shift per lo scrolling
var scrollingPixel = 10; // default

// intervallo per il refresh dello scrolling (in millisecondi)
var scrollingInterval = 35; // default 

//Advanced users: Edit below function to format the RSS feed output as desired
//formatrssmessage(divid, message_index_within_array, linktarget, logicswitch)

function formatrssmessage(divid, msgnumber, linktarget, logicswitch, firstLoad) {
   
	var rsscontent=rsscontentdata[divid][msgnumber]
	var linktitle='<span class="rsstitle"><a href="'+unescape(rsscontent.link)+'" target="'+linktarget+'">'+unescape(rsscontent.title)+'</a></span>'
	var description='<div class="rssdescription">'+unescape(rsscontent.description)+'</div>'
	var feeddate='<span class="rssdate">'+unescape(rsscontent.date)+'</span>'
    
	var newsImageEl = $(newsImage)||false;
	
	// Le prime due news vengono caricate subito una di seguito all'altra. Solo la prima news è effettivamente
	// visualizzata, la seconda viene caricata anticipatamente. Una volta scaduto il timeout viene
	// effettuato lo scrolling in favore della seconda (vedi animateup).
	// Bisogna prevenire che durante l'inizializzazione la seconda chiamata a formatrssmessage da parte della
	// seconda news non sovrascriva l'immagine caricata della prima news, per questo si utilizza la variabile
	// booleana "firstLoad" che serve ad indicare che si e' in presenza della prima news e l'immagine va settata
	if (rsscontent.media != null && firstLoad) {
	    if(newsImageEl){//FC@19.01.2009 check if image element is present
		    newsImageEl.style.display = "block";
		    newsImageEl.alt = rsscontent.mediaNome; // IE
		    newsImageEl.title = rsscontent.mediaNome; // FF
			//newsImageEl.alt = rsscontent.media;
			newsImageEl.src = rsscontent.media;
		}
	} 
		
	if (logicswitch.indexOf("description")!=-1 && logicswitch.indexOf("date")!=-1) //Logic switch- Show description and date
		return linktitle+"<br />"+feeddate+description
	else if (logicswitch.indexOf("description")!=-1) //Logic switch- Show just description
		return linktitle+"<br />"+description
	else if (logicswitch.indexOf("date")!=-1) //Logic switch- Show just date
		return linktitle+"<br />"+feeddate
	else
		return linktitle //Default- Just return hyperlinked RSS title
}

function rsspausescroller(RSS_id, divId, divClass, delay, linktarget, logicswitch) {
	this.tickerid=divId //ID of ticker div to display information
	this.delay=delay //Delay between msg change, in miliseconds.
	this.linktarget=(typeof linktarget!="undefined")? linktarget : ""
	this.logicswitch=(typeof logicswitch!="undefined")? logicswitch : ""
	this.mouseoverBol=0 //Boolean to indicate whether mouse is currently over scroller (and pause it if it is)
	this.hiddendivpointer=1 //index of message array for hidden div
	this.js_is_loaded=0
	this.number_of_tries=0
	
	// MOD mvianello
	// il document.write causa una eccezione perchè essendo le news caricate con una chiamata Ajax asincrona
	// lo stream di output potrebbe gia' essere stato scritto. Si deve quindi utilizzare innerHTML
	
	$(newsContainer).innerHTML='<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden">' +
	                           '	<div class="innerDiv" style="position: relative; width: 100%" id="'+divId+'1">' +
	                           '    	<span style="position: absolute">Initializing RSS scroller...</span>' +
	                           '	</div>' +
	                           '	<div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2">'+
	                           '    </div>' +
	                           '</div>';
	//document.write('<div id="'+divId+'" class="'+divClass+'" style="position: relative; overflow: hidden"><div class="innerDiv" style="position: absolute; width: 100%" id="'+divId+'1"><span style="position: absolute">Initializing RSS scroller...</span></div><div class="innerDiv" style="position: absolute; width: 100%; visibility: hidden" id="'+divId+'2"></div></div>')
	
	if (document.getElementById){ //perform basic DOM browser support
		this.do_onjsload()
	}
}

// -------------------------------------------------------------------
// do_onjsload()- Checks if external JS containing RSS feed is loaded yet
// -If not, continue to check until yes, or abort after certain tries.
// -------------------------------------------------------------------

rsspausescroller.prototype.do_onjsload=function() {
	var scrollerinstance=this
	
	this.tickerdiv=document.getElementById(this.tickerid)
	this.visiblediv=document.getElementById(this.tickerid+"1")
	this.hiddendiv=document.getElementById(this.tickerid+"2")
	this.visibledivtop=parseInt(rsspausescroller.getCSSpadding(this.tickerdiv))
	//set width of inner DIV to outer DIV width minus padding (padding assumed to be top padding x 2)
	this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
	this.visiblediv.innerHTML=formatrssmessage(this.tickerid, 0, this.linktarget, this.logicswitch, true)
	this.hiddendiv.innerHTML=formatrssmessage(this.tickerid, 1, this.linktarget, this.logicswitch)
	this.do_ondivsinitialized()
}

// -------------------------------------------------------------------
// do_ondivsinitialized()- Checks if two divs of scroller is each populated with RSS message yet
// -If not, continue to check until yes, or abort after certain tries.
// -------------------------------------------------------------------

rsspausescroller.prototype.do_ondivsinitialized=function() {
	var scrollerinstance=this
	
	if (parseInt(this.visiblediv.offsetHeight)==0 || parseInt(this.hiddendiv.offsetHeight)==0)
		setTimeout(function(){scrollerinstance.do_ondivsinitialized()}, 100)
	else
		this.initialize()
}

// -------------------------------------------------------------------
// initialize()- Initialize scroller method.
// -Get div objects, set initial positions, start up down animation
// -------------------------------------------------------------------

rsspausescroller.prototype.initialize=function(){
	var scrollerinstance=this
	this.getinline(this.visiblediv, this.hiddendiv)
	this.hiddendiv.style.visibility="visible"
	//set width of inner DIVs to outer DIV's width minus padding (padding assumed to be top padding x 2)
	this.visiblediv.style.width=this.hiddendiv.style.width=this.tickerdiv.offsetWidth-(this.visibledivtop*2)+"px"
	this.tickerdiv.onmouseover=function(){scrollerinstance.mouseoverBol=1}
	this.tickerdiv.onmouseout=function(){scrollerinstance.mouseoverBol=0}
	
	if (window.attachEvent) //Clean up loose references in IE
		window.attachEvent("onunload", function(){scrollerinstance.tickerdiv.onmouseover=scrollerinstance.tickerdiv.onmouseout=null})
	
	setTimeout(function(){scrollerinstance.animateup()}, this.delay)
}


// -------------------------------------------------------------------
// animateup()- Move the two inner divs of the scroller up and in sync
// -------------------------------------------------------------------

// quando inizia lo scrolling in favore di un'altra news deve essere caricata
// l'eventuale nuova immagine associata alla news (tale variabile e' settata a true).
// Durante lo scolling invece tale variabile è a false e l'immagine resta la stessa.
// Inizialmente tale variabile è a true perche' la funzione animateup viene chiamata
// per la prima volta per iniziare lo scrolling dalla prima alla seconda news, e quindi
// l'immagine deve essere cambiata
var changeImageSrc = true;

rsspausescroller.prototype.animateup=function() {
	
	if (changeImageSrc) {
        var nextNews = this.hiddendivpointer;
        var rsscontent=rsscontentdata['nodiItems'][nextNews];
        
		var newsImageEl = $(newsImage)||false;
	
		if (rsscontent.media != null) {
			if(newsImageEl){//FC@19.01.2009 check if image element is present
			    newsImageEl.style.display = "block";
				newsImageEl.alt = rsscontent.mediaNome; // IE
				newsImageEl.title = rsscontent.mediaNome; // FF
				newsImageEl.src = rsscontent.media;
			}
		} else if(newsImageEl){//FC@19.01.2009 check if image element is present
			newsImageEl.style.display = "none";	
		}			
	}
	
	var scrollerinstance=this
	
	if (parseInt(this.hiddendiv.style.top)>(this.visibledivtop+scrollingPixel)) {
		this.visiblediv.style.top=parseInt(this.visiblediv.style.top)-scrollingPixel+"px"
		this.hiddendiv.style.top=parseInt(this.hiddendiv.style.top)-scrollingPixel+"px"
		changeImageSrc = false;
		setTimeout(function(){scrollerinstance.animateup()}, scrollingInterval)
	}
	else {
		this.getinline(this.hiddendiv, this.visiblediv)
		this.swapdivs()
		changeImageSrc = true;
		setTimeout(function(){scrollerinstance.rotatemessage()}, this.delay)
	}
}

// -------------------------------------------------------------------
// swapdivs()- Swap between which is the visible and which is the hidden div
// -------------------------------------------------------------------

rsspausescroller.prototype.swapdivs=function() {
	//alert("rsspausescroller.prototype.swapdivs");
	var tempcontainer=this.visiblediv
	this.visiblediv=this.hiddendiv
	this.hiddendiv=tempcontainer
}
	
rsspausescroller.prototype.getinline=function(div1, div2) {
	//alert("rsspausescroller.prototype.getinline");
	div1.style.top=this.visibledivtop+"px"
	div2.style.top=Math.max(div1.parentNode.offsetHeight, div1.offsetHeight)+"px"
}

// -------------------------------------------------------------------
// rotatemessage()- Populate the hidden div with the next message before it's visible
// -------------------------------------------------------------------

rsspausescroller.prototype.rotatemessage=function() {
	//alert("rotatemessage");
	var scrollerinstance=this
	
	if (this.mouseoverBol==1) //if mouse is currently over scoller, do nothing (pause it)
		setTimeout(function(){scrollerinstance.rotatemessage()}, 100)
	else {
		var i=this.hiddendivpointer
		var ceiling=rsscontentdata[this.tickerid].length
		this.hiddendivpointer=(i+1>ceiling-1)? 0 : i+1
		this.hiddendiv.innerHTML=formatrssmessage(this.tickerid, this.hiddendivpointer, this.linktarget, this.logicswitch)
		this.animateup()
	}
}

rsspausescroller.getCSSpadding=function(tickerobj){ //get CSS padding value, if any
    //alert("rsspausescroller.getCSSpadding");
	if (tickerobj.currentStyle)
		return tickerobj.currentStyle["paddingTop"]
	else if (window.getComputedStyle) //if DOM2
		return window.getComputedStyle(tickerobj, "").getPropertyValue("padding-top")
	else
		return 0
}

function GetRSS(newsContainerId, newsImageId, newsConfigId, newsViewTimePar, scrollingPixelPar, scrollingIntervalPar) {
    newsContainer = newsContainerId;
    newsImage = newsImageId;
    
    if ( newsViewTimePar != null )
    	newsViewTime = newsViewTimePar;
    
    if ( scrollingPixelPar != null )
    	scrollingPixel = scrollingPixelPar;
    
    if ( scrollingIntervalPar != null ) 
    	scrollingInterval = scrollingIntervalPar;
    
	// Get RSS from RSSFeed.do
	var ajax = new Ajax.Request('/' + window.w3gContex + '/RSSFeed.do?'+newsConfigId, {
    	method: 'get',
    	postBody: newsConfigId,
    	onSuccess: function(response) { },    
        onComplete: function(response) {     
        	// verifica della validità dell'XML restituito dal server
		    if(response.responseXML) {
		        // Parserizza il feed XML
		    	ParseXMLFeed(response.responseXML);
		    	new rsspausescroller("", "nodiItems", "rssclass", newsViewTime, "", "description");
		    } //else
		    	//alert('XML NON valido');
		 }	
	   })
}

function ParseXMLFeed(xml) {
      
	// Ottengo la lista degli item
  	var items = xml.getElementsByTagName("item");
  
  	var risultato = "";

 	// ciclo di lettura degli elementi
 	for(var a = 0, b = items.length; a < b; a++) {	 
  		rsscontentdata.nodiItems[a] = ({
    		title: leggiContenuto(items[a], "title"),
    		link: leggiContenuto(items[a], "guid"),
    		date: leggiContenuto(items[a], "pubDate"),
    		description: leggiContenuto(items[a], "description"),
    		// ottiene l'attributo url del tag enclosure e non il suo contenuto
    		media: leggiAttributo(items[a], "enclosure", "url"),
    		mediaNome: leggiAttributo(items[a], "enclosure", "nome")
   		});
  	}
}

// funzione per leggere il contenuto presente all'interno di un nodo XML
// 2008.03.17@FV FIX gestione dati mancanti
function leggiContenuto(item, nomeNodo) {
	var contenuto = "";
	try {
		contenuto = item.getElementsByTagName(nomeNodo).item(0).firstChild.nodeValue;
	} catch (e) {}
	return contenuto;
}
	 
// funzione per leggere il valore di un attributo di un nodo XML	 
function leggiAttributo(item, nomeNodo, nomeAttributo) {
	var tag = item.getElementsByTagName(nomeNodo).item(0);
	 	
	if (tag != null ) {
		var attributo = tag.getAttribute(nomeAttributo);
		return attributo; 
	}
	else
		return null;	
}

	 


