var current_playing='';
var soundz='';
var oldi='';
var current;
currentplayer = '';
currentlength = '';
currrentstate='';
	
function loadFlash(){
	
	
	
	var obj = new Swiff('/wp-content/themes/blastsite/js/cplayer.swf', {
	    id: 'soundz',
	    container:'playercontainer',
	    width: 1,
	    height: 1,
	    params: {
	        wmode: 'transparent',
	        bgcolor: '#ffffff',
	        allowscriptaccess:'always',
	        allowfullscreen:'true'
	    },
	    vars: {
	       file:'',
	       title: 'blastplayer',
	        autostart : false,
	        controlbar : 'bottom'
	      }


	    
	});
	
	/*obj.inject(document.body,'top');*/

	return obj;
	
	/*new Elemen*/
}


function playerReady(obj) 
{
	
	

	/* $('soundz').addModelListener("LOADED", "itemReady");*/
	/* $('soundz').addModelListener("META", "itemLoading");*/
	 $('soundz').addModelListener("TIME", "posAction");
	 $('soundz').addModelListener("STATE", "stateAction");
	 $('soundz').addControllerListener("VOLUME", "stateVolume");
}


function stateAction(obj)
{
		
	if(!currentplayer)
		return;
		
		
	/*if(currentplayer!=lastplayer)
	{
			lastplayer = currentplayer;
		loadplay($$('#'+currentplayer+' .play')[0].getproperty('rel'));
	
	 	
	 } */
	$$('.clrzplayer').removeClass('isplay');
	currrentstate = obj.newstate;
		
	if(obj.newstate=='BUFFERING')
		$$('#'+currentplayer).removeClass('isplay').removeClass('ispause').addClass('isload');
	if(obj.newstate=='PLAYING')
		$$('#'+currentplayer).removeClass('ispause').removeClass('isload').addClass('isplay');
	if(obj.newstate=='PAUSED')
		$$('#'+currentplayer).removeClass('isplay').removeClass('isload').addClass('ispause');
	if(obj.newstate=='COMPLETED')
		$$('#'+currentplayer).removeClass('isplay').removeClass('isload').addClass('ispause');
		
	if(obj.newstate=='COMPLETED')
	{
		
		if($(currentplayer).hasClass('clrzplaylistplayer'))
		{
			
			$$('#'+currentplayer+' .next').fireEvent('click');
			
		}
	}
}

function stateVolume(obj)
{
	
	
	
	
}




function loadplay(song)
{
	
	
	if(song==current_playing)
	{
		$('soundz').sendEvent('PLAY');

		return;
	}
	
	current_playing=song;

       

	
	var chain=song;
	$('soundz').sendEvent('LOAD', chain);
	/*$('soundz').sendEvent('PLAY');*/
	
}


/*function itemLoading(obj)
{
	
	
	if(obj.info=='NetStream.Play.Start')
		$('remote').removeClass('load').addClass('pause');
		
}*/

/*function itemReady(obj)
{
	console.log('sdf');
	
	console.log(obj.offset);
	
}*/

function pad(number, length) {
   
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
   
    return str;

}

function posAction(obj)
{
	currentlength = obj.duration;
	var percent = (obj.position/obj.duration)*100;
	var seconds = (obj.position).round(0);
	var seconds_dur = (obj.duration).round(0);
	
	
	
	var timing =  Math.floor(seconds / 60) + ":" + pad((seconds % 60).toFixed(),2) ;
	var during = 	Math.floor(seconds_dur / 60) + ":" + pad((seconds_dur % 60).toFixed(),2) ;
	var time_width = $$('#'+currentplayer+' div.timeline')[0].getWidth();
	
	$$('#'+currentplayer+' .title marquee')[0].set('html',$$('#'+currentplayer+' .play')[0].getProperty('title')+' '+ timing +' / '+during );
		$$('#'+currentplayer+' .timeline span')[0].morph({'width':((time_width*percent)/100)});
		
	/*if(obj.position>=pos[part+1])
	$('soundz').sendEvent('PLAY');*/

}	

function PlayerSeek(percent)
{
	
	$('soundz').sendEvent('SEEK', ((currentlength*percent)/100));
	
}

function PlayerVolume(percent)
{
	
	$('soundz').sendEvent('VOLUME', percent);
	
}

function initPlayer(elid)
{
	
	var timelinespan = $$('#'+elid+' .timeline span')[0];
	var timelinecontainer = $$('#'+elid+' .timeline')[0];
	var titlecontainer = $$('#'+elid+' .title')[0];
	var timeevents = [titlecontainer,timelinecontainer];
	
	timelinespan.set('morph', {duration: 300, wait: false});

	
	var volumespan = $$('#'+elid+' .volume span')[0];
	var volumecontainer = $$('#'+elid+' .volume')[0];
	volumespan.set('morph', {duration: 300, wait: false});

        /* PRECEDENTE SONG */
	$$('#'+elid+' a.previous').addEvent('click',function(e){
          
            $$('#clrzplaylist li a').each(function(el,i){
               
                if(current_playing==el.getProperty('rel')){
                    scurrent = i;
                }
               
            });
            var prev="";
            if($$('#clrzplaylist li a')[(scurrent-1)])
            	prev = $$('#clrzplaylist li a')[(scurrent-1)];
            else
            	prev = $$('#clrzplaylist li a')[0];
            	
            	prev.fireEvent('click');
            
            
        });

        /* NEXT SONG */
	$$('#'+elid+' a.next').addEvent('click',function(e){
           
            var scurrent = -1;
            $$('#clrzplaylist li a').each(function(el,i){
               
                if(current_playing==el.getProperty('rel')){
                    scurrent = i;
                }
            });
             var next="";
            if($$('#clrzplaylist li a')[(scurrent+1)])
            	next = $$('#clrzplaylist li a')[(scurrent+1)];
            else
            	next = $$('#clrzplaylist li a')[0];
            	
            	next.fireEvent('click');
            
          
        });

	
	$$('#'+elid+' a.play').addEvent('click',function(e){
		
				if(currentplayer!=elid)
				{
					
					loadplay($$('#'+elid+' .play')[0].getProperty('rel'));
	
	 	
	 			}
                currentplayer = elid;
		 
		$('soundz').sendEvent('PLAY');
		
		});
	
	timeevents.each(function(el,i){
		el.addEvent('mousedown', function(event){
		event = new Event(event);
                currentplayer = elid;
		var posx = (event.page.x - timelinecontainer.getLeft());
		PlayerSeek(posx/timelinecontainer.getWidth()*100);
		
		timelinespan.morph({'width': posx});
		event.stop();
	});
	});

	volumecontainer.addEvent('mousedown', function(event){
		event = new Event(event);
		
		var posx = (event.page.y - (volumecontainer.getTop()) );
		PlayerVolume(100-(posx/volumecontainer.getHeight()*100));
		
		volumespan.morph({'margin-top': posx});
		event.stop();
	});
	
	
/*startticker();*/
			
}



/* SCROLLBAR FUNCTION */
function makeScrollbar(content,scrollbar,handle, arrowtop, arrowbottom,horizontal,ignoreMouse){
        var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		/* Scroll the content element when the mousewheel is used within the
		content or the scrollbar element.*/
		$$(content, scrollbar).addEvent('mousewheel', function(e){
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 13;
			slider.set(step);
		});
	}

        if(arrowtop){
            $$(arrowtop).addEvent('click', function(e){
                    e = new Event(e).stop();
                    var step = slider.step - 13;
                    slider.set(step);
            });
        }
        if(arrowtop){
            $$(arrowbottom).addEvent('click', function(e){
                    e = new Event(e).stop();
                    var step = slider.step + 13;
                    slider.set(step);
            });
        }



}



function createPlayers()
{
	//<div class="clrzplayer" id="player1"></div>
	if(!$$('a.dlmp3'))
	return;
	$$('a.dlmp3').each(function(el,inc){
		var pl = '<a class="play" title="{pltitle}" rel="{plrel}">play/pause</a>	<div id="titleoverflow" class="titleoverflow"> <div id="titlecontainer" class="titlecontainer"> <div class="title"> <marquee scrollamount="2">  {pltitle} </marquee>  </div> </div> </div><div class="timeline"><span></span></div><div class="equalizer"></div><div class="volume"><div class="volumemask"></div><span></span></div><div class="link-popup"><div class="popupmask"></div><a class="open-popup" href="http://blastmu.feed.colorz.fr/webservice/?action=playersingle&rel={plrel}&titre={pltitle}">Popup</a><p class="close-popup">close</p> </div>';	
	
		var obj = {pltitle:el.get('html'),plrel:el.getProperty('href')};
		
		/* test*/
	new Element('div',{
		id:'playerdyn'+inc,
		}).addClass('clrzplayer').addClass('playersingle')
		.set('html',pl.substitute(obj))
		.inject(el,'after');
	
	el.destroy();
		});
	
	
}


window.addEvent('domready',function(e){
createPlayers();
        if($('clrzplaylist')){makeScrollbar( $('clrzplaylist'), $('scrollnone'), $('handnone'), $('top-playlist'),  $('bottom-playlist')  );}

	





	

	
	var mydiv = new Element('div',{id:'playercontainer'}).setStyles({'overflow':'hidden','height':1,'width':1,'position':'absolute','left':0,'top':window.getScrollTop().toInt()});
	var linkFX = [];

        


	/*mydiv.adopt(obj);*/
	mydiv.inject($(document.body),'bottom');


	 loadFlash();


         $$('.clrzplayer').each(function(el,i){
           
           initPlayer(el.getProperty('id'));

        });
	 
	 if($('player1'))
	 {
		/*initPlayer('player1');*/
	 	$$('#player1 a.play').addEvent('mousedown',function(e){
		 
		 
		 currentplayer = 'player1';
		 if(this.getProperty('rel')!=current_playing)
		 loadplay(this.getProperty('rel'));

		
		 
		 });
	 }
	 
	 
		/*initPlayer('player2');*/
	 	$$('ul.clrzplaylist li a').addEvent('click',function(e){

                 currentplayer = this.getParent().getParent().getProperty('rel');
               
		 $$('#'+currentplayer+' a.play')[0].setProperty('title',this.get('html'));
		 $$('#'+currentplayer+' a.play')[0].setProperty('rel',this.getProperty('rel'));
		 
		 
		 loadplay(this.getProperty('rel'));
		 $('soundz').sendEvent('PLAY');
		 
		 
                    /*startMoorquee();*/
                    /*startticker();*/
		 
		 });
	 
	 
		 $$('.clrzplaylistplayer .play').each(function(btplay,inc){
			 
			 btplay.addEvent('click',function(e){
			
			
			 if(this.getProperty('rel'))
			 return;
			 
			  
			
			 this.setProperty('title',$$('ul.clrzplaylist li a')[inc].get('html'));
			  loadplay($$('ul.clrzplaylist li a')[inc].getProperty('rel'));
			 $('soundz').sendEvent('PLAY');
			 });
		 });
		 	 
/*$$('.clrzplay').each(function(el,i){
	
	linkFX[i] = new Fx.Morph(el,{duration:300,transition: Fx.Transitions.Back.easeIn,wait:false});
	
	
	el.addEvent('click',function(e){
								

								var thelink = this;
								new Event(e).stop();
	
	
								if(thelink.getProperty('rel')==current_playing)
								{
									
										$('soundz').sendEvent('PLAY');
									return;
								}
								current = this;
								
							if(linkFX[oldi])
							{
								linkFX[oldi].start({'padding-left':0});
								$$('.clrzplay')[oldi].removeClass('pause').removeClass('load').removeClass('play');
							}
								
								linkFX[i].start({'padding-left':15}).chain(function(){
									
									loadplay(thelink.getProperty('rel'));
									
								});
									 
// 																								remoteFX.start({'width':0,'opacity':0}).chain(function(){
// 																									elremote.inject(thelink,'top');
// 																								    linkFX[i].set({'padding-left':0});                 
// 																								remoteFX.set({'width':15});
// 																								remoteFX.start({'width':15,'opacity':1});
// 																								  
// 																								loadplay(thelink.getProperty('rel'));
// 																								});   
	
					oldi =  i;
	
	
						});
	
	
	
	
	
	});
*/



//loadFlash('mp3_test.mp3');







    $$('.link-popup a.open-popup').each(function(el,i){
        el.addEvent('click',function(e){
           new Event(e).stop();
           var player1 = window.open(this.href, 'player1', 'height=58, width=330, top='+(el.getParent('.clrzplayer').getTop()-window.getHeight())+', left='+el.getParent('.clrzplayer').getPosition().x+', toolbar=no, menubar=no, location=no, resizable=no, scrollbars=no, status=no');
          
           if(currrentstate=='PLAYING')
           $('soundz').sendEvent('PLAY');
           /*this.removeClass('open-popup');
             *
           this.addClass('close-popup');*/
          
        });
    });





    /*$$('.link-popup a.close-popup').each(function(el,i){
        el.addEvent('click',function(e){
            player1.close();
            e.stop();
        });
    });*/

    $$('.link-popup2 a.open-popup').each(function(el,i){
        el.addEvent('click',function(e){
           var player2 = window.open(this.href, 'player2', 'height=245, width=330, top='+(el.getParent('.clrzplaylist_background').getTop()-window.getHeight())+', left='+el.getParent('.clrzplaylist_background').getPosition().x+', toolbar=no, menubar=no, location=no, resizable=no, scrollbars=no, status=no');
           /*this.removeClass('open-popup');

           this.addClass('close-popup');*/
           e.stop();
        });
    });
    /*$$('.link-popup2 a.close-popup').each(function(el,i){
        el.addEvent('click',function(e){
            player2.close();
            e.stop();
        });
    });*/

      


});

function playerpopupclosed(){
    alert('test');
}



var tWidth='300px';                  // width (in pixels)
var tHeight='25px';                  // height (in pixels)
var tcolour='#ffffcc';               // background colour:
var moStop=true;                     // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3;                        // scroll speed (1 = slow, 5 = fast)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=tSpeed;
var aw, mq;
var fsz = parseInt(tHeight) - 4;

function startticker(){
    if (document.getElementById) {
        var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"';
        if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=tSpeed"';
        tick +='><div id="mq" style="position:absolute;left:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>';
        document.getElementById('ticker').innerHTML = tick;
        mq = document.getElementById("mq");
        mq.style.left=(parseInt(tWidth)+10)+"px";
        mq.innerHTML='<span id="tx">'+content+'<\/span>';
        aw = document.getElementById("tx").offsetWidth;
        lefttime=setInterval("scrollticker()",50);
    }
}

    function scrollticker(){
        mq.style.left = (parseInt(mq.style.left)>(-10 - aw)) ?parseInt(mq.style.left)-cps+"px" : parseInt(tWidth)+10+"px";
    }

