/* ===========================================================================
[Radio Widget Browser]

Project:		105 messenger
Version:		0.0.0.1.8
Last change:	10/03/09 [commentate view photo,classifiche, mdp]
Assigned to:	Marcello De Palo (mdp) marcellodepalo@gmail.com
Primary use:	messenger
=========================================================================== */

Effect.DefaultOptions.duration = 0.3;


// ===========================================================================
// RADIO MANAGER
// ===========================================================================
RadioBrowser=Class.create();
RadioBrowser.prototype={

	baseURI:'',

	categories:null,
	widgets:null,

	categoryColumn:null,
	radioColumn:null,
	infoColumn:null,
	padColumn:null,

	currentCategory:null,
	currentRadio:null,
	currentOnAir:null,
    currentPlayer: null,

	initialize:function(baseURI,indexFile,browserPanel){

		this.baseURI=baseURI;

		this.categories=[];
		this.widgets={};

		new Ajax.Request(baseURI+indexFile,{
			method:'get',
			onSuccess:this.showCategories.bind(this)
		});

		var panel=$(browserPanel);

		var columns=panel.getElementsByTagName('div');

		this.categoryColumn=columns[0];
		this.radioColumn=columns[1];
		this.infoColumn=columns[2];
		this.padColumn=$('pad-browser');
		
	},

	showCategories:function(response){

		var categoryNodes=response.responseXML.getElementsByTagName('category');

		var categoryList=document.createElement('ul');

		this.categoryColumn.parentNode.replaceChild(categoryList,this.categoryColumn);
		this.categoryColumn=categoryList;

		for(var i=0;i<categoryNodes.length;i++){

			var categoryNode=categoryNodes[i];

			var title=categoryNode.getElementsByTagName('title')[0].firstChild.nodeValue;
			var xmlFile=categoryNode.getElementsByTagName('xml_file')[0].firstChild.nodeValue;
			var avatar=categoryNode.getElementsByTagName('image')[0].firstChild.nodeValue;

			var category=new RadioCategory(title,xmlFile,avatar);
			this.categories.push(category);

			var categorySelect=function(category){

				return(function(){

					if(this.currentCategory==category){
						return;
					}

					this.closeCurrentCategory();

					if(!category.hasWidgets()){

						var widgetsSource=this.baseURI+category.xmlFile+'?timestamp='+new Date().getTime();

						new Ajax.Request(widgetsSource,{
							method:'get',
							onSuccess:function(response){
								category.populateWidgets(response,this);
								this.showWidgets(category);
							}.bind(this)});

					}else{
						this.showWidgets(category);
					}

				});
			};

			Event.observe(category.node,'click',categorySelect(category).bind(this));
			Event.observe(category.node,'mouseover',category.mouseOver.bind(category));
			Event.observe(category.node,'mouseout',category.mouseOut.bind(category));
			this.categoryColumn.appendChild(category.node);

		}


	},

	showWidgets:function(category){
		this.currentCategory=category;
		var widgetList=document.createElement('ul');
		this.radioColumn.parentNode.replaceChild(widgetList,this.radioColumn);
		this.radioColumn=widgetList;
		this.currentCategory.open(this.radioColumn);

		//if($('sceltixte').style.display != "block")
		//	$('sceltixte').hide();
	},

	showWidget:function(widget){
		this.closeCurrentRadio();
		this.currentRadio=widget;
		this.currentRadio.open();

        this.currentPlayer = new MyPlayer(widget.player);
        this.currentPlayer.load(widget.streaming);

		//MD 11-11-2008
		//this.currentOnAir=new OnAir(widget.onair);
		//this.currentOnAir.open();

		this.infoColumn.parentNode.replaceChild(this.currentRadio.infoNode,this.infoColumn);
		this.infoColumn=this.currentRadio.infoNode;
	    this.padColumn.parentNode.replaceChild(this.currentRadio.padNode,this.padColumn);
	    this.padColumn=this.currentRadio.padNode;
	},

	closeCurrentCategory:function(){
		this.closeCurrentRadio();
		if(this.currentCategory!=null){
			this.currentCategory.close();
			this.currentCategory=null;
		}
	},

	closeCurrentRadio:function(){
        this.closeCurrentPlayer();

        //MD 11-11-2008
		//this.closeCurrentOnAir();

		if(this.currentRadio!=null){
			this.currentRadio.close();
			this.currentRadio=null;
			
			// content: OnAir, Info Radio, Streaming
			var blank=document.createElement('div');
			this.infoColumn.parentNode.replaceChild(blank,this.infoColumn);
			this.infoColumn=blank;

			var blank=document.createElement('div');
			this.padColumn.parentNode.replaceChild(blank,this.padColumn);
			this.padColumn=blank;
		}
	},
	
	closeCurrentOnAir:function(){
		if(this.currentOnAir!=null){
		  this.currentOnAir.stop();
		  this.currentOnAir = null;
		}
	},

    closeCurrentPlayer: function() {
        if (this.currentPlayer != null) {
            this.currentPlayer.stop();
            this.currentPlayer = null;
        }
    }

};

// ===========================================================================
// WEB RADIO MANAGER
// ===========================================================================
RadioCategory=Class.create();
RadioCategory.prototype={

	title:'',
	xmlFile:'',
	node:null,
	widgets:null,

	initialize:function(title,xmlFile,avatar){
		this.title=title;
		this.xmlFile=xmlFile;
		this.node=document.createElement('li');
		Element.addClassName(this.node,avatar);
		this.node.appendChild(document.createTextNode(this.title));
		this.widgets=[];
	},

	hasWidgets:function(){
		return(this.widgets.length>0);
	},

	open:function(radioColumn){
		Element.addClassName(this.node,'active');
		for(var i=0;i<this.widgets.length;i++){
			radioColumn.appendChild(this.widgets[i].node)
		}
	},

	close:function(){
		Element.removeClassName(this.node,'active');
	},

	mouseOver:function(){
		Element.addClassName(this.node,'hover');
	},

	mouseOut:function(){
		Element.removeClassName(this.node,'hover');
	},

	populateWidgets:function(response,browser){
		var widgetNodes=response.responseXML.getElementsByTagName('webradio');

		for(var i=0;i<widgetNodes.length;i++){
			var widgetNode= widgetNodes[i];
			var idNumber 	= widgetNode.getAttribute('id');
			var name		= widgetNode.getAttribute('name');
			var avatar      = widgetNode.getAttribute('avatar');
			var claim      	= widgetNode.getAttribute('claim');

			var widget		= new Radio(idNumber,name,avatar,claim);

			
			var selectWidget=function(widget){
				return(function(){
					if(this.currentRadio==widget){
						return;
					}

					widget.open();

					if(typeof(this.widgets[widget.idNumber])=='undefined'){
						var widgetSource=browser.baseURI+'webradio/'+widget.xmlFile+'?timestamp='+new Date().getTime();
						new Ajax.Request(widgetSource,{
							method:'get',
							onSuccess:function(response){
								widget.populate(response);
								this.widgets[widget.idNumber]=widget;
								this.showWidget(widget);
							//}.bind(this)});
				            }.bind(this),
				            onFailure: function() {
                                alert('spiacenti');
				            }}
		                );
							
					}
					else{
						this.showWidget(widget);
					}
				});
			};

			Event.observe(widget.node,'click',selectWidget(widget).bind(browser));
			Event.observe(widget.node,'mouseover',widget.mouseOver.bind(widget));
			Event.observe(widget.node,'mouseout',widget.mouseOut.bind(widget));

			this.widgets.push(widget);
		}
	}
};

// ===========================================================================
// RADIO MANAGER
// ===========================================================================
Radio=Class.create();
Radio.prototype = {

    idNumber: null,
    title: '',
    claim: '',
    xmlFile: '',

    briefDescription: '',
    onair: '',
    streaming: '',
    player: '',

    image: '',

    node: null,
    infoNode: null,
    padNode: null,

    initialize: function(idNumber, title, avatar, claim) {

        this.idNumber = idNumber;

        this.xmlFile = idNumber + '.xml';
        this.title = title;
        this.claim = claim;

        this.node = document.createElement('li');
        Element.addClassName(this.node, avatar);
        this.node.appendChild(document.createTextNode(this.title));
		$('message').hide();
    },

    open: function() {
        Element.addClassName(this.node, 'active');
    },

    close: function() {
        Element.removeClassName(this.node, 'active');
    },

    mouseOver: function() {
        Element.addClassName(this.node, 'hover');
    },

    mouseOut: function() {
        Element.removeClassName(this.node, 'hover');
    },

    populate: function(response) {
        
        var radioInfo = response.responseXML.getElementsByTagName('webradio')[0];

        this.streaming = radioInfo.getElementsByTagName('streaming')[0].firstChild.nodeValue;
		
		//MD 11-11-2008
        //this.onair = radioInfo.getElementsByTagName('onair')[0].firstChild.nodeValue;

        this.briefDescription = radioInfo.getElementsByTagName('brief_description')[0].firstChild.nodeValue;

        this.image = radioInfo.getElementsByTagName('image')[0].firstChild.nodeValue;

        this.player = document.getElementById("wmp");

        this.infoNode = document.createElement('div');

        this.padNode = document.createElement('div');
        this.padNode.setAttribute('id', 'pad');

        var image = document.createElement('img');
        image.setAttribute('src', 'images/ui/b/' + this.image);
        image.setAttribute('width', 100);
        image.setAttribute('height', 100);
        this.infoNode.appendChild(image);

        this.infoNode.appendChild(document.createTextNode(this.title));

        if(this.claim){
	        var pclaim = document.createElement('p');
    	    Element.addClassName(pclaim, 'claim');
	        pclaim.appendChild(document.createTextNode(this.claim));
	        this.infoNode.appendChild(pclaim);
		}

		
		//MD 11-11-2008
        //var nowplaying = document.createElement('div');
        //Element.addClassName(nowplaying, 'nowplaying');
        ///nowplaying.setAttribute('id', 'nowplaying');
        //this.infoNode.appendChild(nowplaying);


        var description = document.createElement('p');
        Element.addClassName(description, 'descrizione');
        description.setAttribute('id', 'desc');
        description.innerHTML = this.briefDescription;
        this.infoNode.appendChild(description);


        var emailImg = document.createElement('img');
        emailImg.setAttribute('src', 'images/WLHotmail120x70_2.jpg');
        emailImg.setAttribute("class", "btn");
        emailImg.setAttribute("border", 0);
        
		
        var email = document.createElement('a');
        Element.addClassName(email, 'email');
        email.setAttribute("href", "mailto:?body=Ciao, ti segnalo una nuova iniziativa all\'interno di Windows Live Messenger.\r\n Mentre comunichi con i tuoi amici ora puoi ascoltare la United Music Messenger Radio selezionandola dal menu\' attivita\'.\r\n Ci sono piu\' di 30 webradio, scegli la tua preferita...e mettiti in ascolto con i tuoi amici. E\' gratis! \r\nhttp://messenger.msn.com/Resource/games.aspx?appID=99995890");
        email.setAttribute("target", "_blank");
        email.appendChild(emailImg);
        //email.appendChild(document.createTextNode("Segnala questa webradio a un amico"));

        var activity1 = document.createElement('p');
        Element.addClassName(activity1, 'activity');
        activity1.setAttribute('id', 'activity');
        activity1.appendChild(email);


		// activity 2        
		var url = "http://spaces.live.com/BlogIt.aspx?Title=" + this.title + 
			"&SourceURL=" + escape(window.location.href) +  "&description=" + "Vi segnalo una nuova iniziativa all'interno di Windows Live Messenger.<br>Mentre comunichi con i tuoi amici ora puoi ascoltare la United Music Messenger Radio selezionandola dal menu' attivita'.<br>Ci sono piu' di 30 webradio, scegli la tua preferita...e mettiti in ascolto con i tuoi amici. E' gratis!" + 
			"<br><br><a style=\"color:red;\" href='http://messenger.msn.com/Resource/games.aspx?appID=99995890'>Provala ora</a>";

        var blogImg = document.createElement('img');
        blogImg.setAttribute('src', 'images/WLSpaces120x70_1.jpg');
        blogImg.setAttribute("class", "btn");
        blogImg.setAttribute("border", 0);
        
        
        var blog = document.createElement('a');
        Element.addClassName(blog, 'blog');
        blog.setAttribute("href", url);
        blog.setAttribute("target", "_blank");
        blog.appendChild(blogImg);
        //blog.appendChild(document.createTextNode("Invia al tuo Blog questa webradio"));


        var activity2 = document.createElement('p');
        Element.addClassName(activity2, 'activity');
        activity2.setAttribute('id', 'activity');
        activity2.appendChild(blog);


		// activity 3
        var buddyImg = document.createElement('img');
        buddyImg.setAttribute('src', 'images/WLMessenger120x70_1.png');
        buddyImg.setAttribute("class", "btn");
        buddyImg.setAttribute("border", 0);

        var buddy = document.createElement('a');
        Element.addClassName(buddy, 'blog');
        buddy.setAttribute("href", 'javascript:IMStart(99995890);');
        buddy.appendChild(buddyImg);

        var activity3 = document.createElement('p');
        Element.addClassName(activity3, 'activity');
        activity3.setAttribute('id', 'activity');
        activity3.appendChild(buddy);
      
      
        this.infoNode.appendChild(activity1);
        this.infoNode.appendChild(activity2);
        this.infoNode.appendChild(activity3);
		



        if (response.responseXML.getElementsByTagName('video').length > 0 || 
			response.responseXML.getElementsByTagName('foto').length > 0 || 
			response.responseXML.getElementsByTagName('classifica').length > 0 || 
			response.responseXML.getElementsByTagName('radionews').length > 0) 
			{
        		//pad
        		//$('sceltixte').show();
		        if (response.responseXML.getElementsByTagName('video').length > 0) {
		            this.populateVideo(response.responseXML.getElementsByTagName('video'));
		        }

		        /*
		        if (response.responseXML.getElementsByTagName('foto').length > 0) {
		            this.populateFoto(response.responseXML.getElementsByTagName('foto'));
		        }

		        if (response.responseXML.getElementsByTagName('classifica').length > 0) {
		            this.populateClassifiche(response.responseXML.getElementsByTagName('classifica'));
		        }

		        if (response.responseXML.getElementsByTagName('radionews').length > 0) {
		            this.populateRadionews(response.responseXML.getElementsByTagName('radionews'));
		        }
		        */
			}



    },

    populateVideo: function(videoNodes) {
        var video = document.createElement('div');
        Element.addClassName(video, 'video');
        video.setAttribute('id', 'padVideo');
        video.setAttribute('style', 'display:block;');

        for (var i = 0; i < videoNodes.length; i++) {

            var videoNode = videoNodes[i];
            var width = videoNode.getAttribute('width');
            var height = videoNode.getAttribute('height');
            var img = videoNode.getElementsByTagName('image')[0].firstChild.nodeValue;
            var link = videoNode.getElementsByTagName('link')[0].firstChild.nodeValue;

			var a = document.createElement('a');
            a.setAttribute('href', link);
            a.setAttribute('target', '_blank');
            
            

            var image = document.createElement('img');
            image.setAttribute('src', 'images/' + img);
            //image.setAttribute('width', width);
            //image.setAttribute('height', height);
            
            a.appendChild(image);
            
            video.appendChild(a);

        }

        this.padNode.appendChild(video);

    },

    populateFoto: function(fotoNodes) {

        var foto = document.createElement('div');
        Element.addClassName(foto, 'foto');
        foto.setAttribute('id', 'padFoto');
        foto.style.display = "none";

        for (var i = 0; i < fotoNodes.length; i++) {

            var fotoNode = fotoNodes[i];
            var width = fotoNode.getAttribute('width');
            var height = fotoNode.getAttribute('height');
            var img = fotoNode.getElementsByTagName('image')[0].firstChild.nodeValue;
            var link = fotoNode.getElementsByTagName('link')[0].firstChild.nodeValue;

			var a = document.createElement('a');
            a.setAttribute('href', link);
            a.setAttribute('target', '_blank');

            var image = document.createElement('img');
            image.setAttribute('src', 'images/' + img);
            //image.setAttribute('width', width);
            //image.setAttribute('height', height);
            
            a.appendChild(image);
            
            foto.appendChild(a);

        }
        this.padNode.appendChild(foto);

    },

    populateClassifiche: function(classificheNodes) {
        var classifiche = document.createElement('div');
        Element.addClassName(classifiche, 'classifiche');
        classifiche.setAttribute('id', 'padClassifiche');
        classifiche.style.display = "none";

        var ul1 = document.createElement('ul');
        Element.addClassName(ul1, 'classifiche');

        //var ul2 = document.createElement('ul');
        //Element.addClassName(ul2, 'classifiche');
        //ul2.setAttribute('style', 'float:right;');


        for (var i = 0; i < classificheNodes.length; i++) {

            var classificheNode = classificheNodes[i];
            var item = classificheNode.getElementsByTagName('item')[0].firstChild.nodeValue;
            var link = classificheNode.getElementsByTagName('link')[0].firstChild.nodeValue;
            
            
            var li = document.createElement('li');
            li.innerHTML = "<a href=" + link + " target=_blank>" + item + "</a>";
            //li.appendChild(document.createTextNode(item));

            //if (i < 4)
                ul1.appendChild(li);
            //else
            //    ul2.appendChild(li);

        }

        classifiche.appendChild(ul1);
        //classifiche.appendChild(ul2);

        this.padNode.appendChild(classifiche);

    },

    populateRadionews: function(radionewsNodes) {
        var radionewsDiv = document.createElement('div');
        Element.addClassName(radionewsDiv, 'radionews');
        radionewsDiv.setAttribute('id', 'padRadionews');
        radionewsDiv.style.display = "none";

        this.padNode.appendChild(radionewsDiv);
        new News(radionewsNodes, radionewsDiv);

    }

};


MyPlayer = Class.create();
MyPlayer.prototype =
{
    initialize: function(currPlayer) {
        this.currPlayer = currPlayer;
    },

    load: function(url) {
        if (this.currPlayer != null) {
            this.currPlayer.Url = url;
        }
    },

    stop: function() {
        if (this.currPlayer != null) {
            this.currPlayer.controls.stop();
        }
    }
};


OnAir=Class.create();
OnAir.prototype = {

    xmlFile: '',
    pauseLength: 10000,
    timer: 0,

    initialize: function(xml) {
        this.xmlFile = xml;
    },

    open: function() {
        this.build();
    },

    show: function(transport) {
    },

    build: function() {
        this.start();
    },

    start: function() {
        this.interval = setInterval(this.populate.bind(this), this.pauseLength);
    },

    stop: function() {
        clearInterval(this.interval)
    },


    populate: function() {
        var onairSource = this.xmlFile;// + '?timestamp=' + new Date().getTime();
	    new Ajax.Request('messenger_onair.php', {
	      parameters: { record: 1, url: onairSource, template: 3 }, 
			onComplete: function(request) { 
			  $('nowplaying').innerHTML = request.responseText;
			}
	    });
    }


}


News=Class.create();
News.prototype={
	
	tickerDiv: '', 
	tickerTitle: "news-link",
	tickerLink: "/it/hotnews/",
	pauseLength: 6500,
	timer: 0,
	currentTitle: 0,
	items: null,
	
	initialize: function(nodes, radionewsDiv) {
		

		this.tickerDiv = radionewsDiv;
		this.tickerTitle=document.createElement('p');
		this.tickerTitle.setAttribute('id','news-link');
		this.tickerTitle.appendChild(document.createTextNode('news'));
		this.tickerDiv.appendChild(this.tickerTitle);

		this.items = [];
		
		this.parseXML(nodes);
		this.buildTicker();
					
	},
	
	buildTicker: function() {
		// replace the placeholder content with the first news title
		if (this.items[this.currentTitle]) {
			this.tickerTitle.innerHTML = this.items[this.currentTitle]['title'] + "&nbsp;<a href=" + this.items[this.currentTitle]['link'] + " target=_blank>leggi tutto...</a>";
			this.start();// start the timer if we have valid headlines
		}
	},
	
	parseXML: function(xml) {
		// build the array of news titles
		for(var i=0;i<xml.length;i++){
			var radionewsNode	= xml[i];
			title		= radionewsNode.getElementsByTagName('item')[0].firstChild.nodeValue;
			var link    = radionewsNode.getElementsByTagName('link')[0].firstChild.nodeValue;
			this.items.push({title: title, link: link});
		}
	},
	
	start: function() {
		this.interval = setInterval(this.showNext.bind(this), this.pauseLength);
	},
	
	stop: function() {
		clearInterval(this.interval)
	},
	
	showNext: function() {
		//determine next headline
		if ( this.currentTitle < this.items.length-1 ) {
			this.currentTitle = this.currentTitle+1;
		} else {
			this.currentTitle = 0;
		}

		new Effect.Fade(this.tickerTitle, {
			afterFinish: function() {
				this.switchData();
				new Effect.Appear(this.tickerTitle); 
			}.bind(this)});

	},
	
    switchData: function() {
		//$(this.tickerTitle).setAttribute("href", this.tickerLink);
		if (this.items[this.currentTitle]) {
			this.tickerTitle.innerHTML = this.items[this.currentTitle]['title'] + "&nbsp;<a href=" + this.items[this.currentTitle]['link'] + " target=_blank>leggi tutto...</a>";
		}
	}
	
};


// ===========================================================================
// BLOCK MANAGER
// ===========================================================================
var Block = {

    showPad: function(element) {

        var el = document.getElementById(element);
        var ar = document.getElementById("pad").getElementsByTagName("div");
        if (el) {
            if (el.style.display != "block") {
                for (var i = 0; i < ar.length; i++) {
                    ar[i].style.display = "none";
                }
                el.style.display = "block";
            } 
        }
    }

}
Block.editing = false

function IMStart(AppId){
	
    var obj;
    try{
        obj=new ActiveXObject("MSNMessenger.P4QuickLaunch");
    }
    catch(e){
        obj=null;
    }

    if(obj!=null){
    	obj.LaunchApp(AppId,"");
    }
    else{
        alert("Per utilizzare la funzionalit&agrave; occorre Windows Live Messenger 6.0 o superiore &egrave; Internet Explorer 5.5 o superiore.");
    }   
}
