 soundManager.onload = function()
{
	jizzPlayer.roll();
}

soundManager.onerror = function()
{
	jizzPlayer.checkiPhone();

}


//$.preLoadImages("http://static.jizzradio.com/images/logo.png","http://static.jizzradio.com/images/bg1.png","http://static.jizzradio.com/images/followfacebook.png","http://static.jizzradio.com/images/followtwitter.png","http://static.jizzradio.com/images/fondo-calendario.png","http://static.jizzradio.com/images/fondo-jizzblog.png","http://static.jizzradio.com/images/fondo-lamusica.png","http://static.jizzradio.com/images/fondo-jizzfeed.png","http://static.jizzradio.com/images/lineas.gif","http://static.jizzradio.com/images/locura.gif","http://static.jizzradio.com/images/puntitos.gif","http://static.jizzradio.com/images/rayas.gif","http://static.jizzradio.com/images/sicodelia.gif","http://static.jizzradio.com/images/peaks.png","http://static.jizzradio.com/images/stop.png","http://static.jizzradio.com/images/play.png" );


soundManager.url = "http://static.jizzradio.com/swf/";
soundManager.flashVersion = 9;
soundManager.useHighPerformance = true;
soundManager.useFastPolling = true;
soundManager.debugMode = false;

var jizzPlayer = 
{
	soundId:"jizzLive",
	playing:0,
	playingVideo:0,
	stopImg:"http://static.jizzradio.com/images/stop.png",
	playImg:"http://static.jizzradio.com/images/play.png",
	volume:100,
	maxMb:35,
	volInt:10,
	peak:0,
	themeSel:0,
	streamSel:0,
	streamURL:["http://190.54.36.13:8000/jizz.mp3","http://190.54.36.13:8000/jizz256.mp3","http://190.54.36.13:8000/jizz64.mp3"],
	themes:["default","disco","deepspace","cyclops","rayas","puntitos","apples","missjizz","mixtape","420","vivachile"],
	createSound: function()
	{
		if(soundManager.getSoundById(this.soundId) != null) soundManager.destroySound(this.soundId);
			
		var snd = soundManager.createSound({	
					id: this.soundId,
					url: this.streamURL[this.streamSel],
					volume: this.volume,
					usePeakData: true,
					whileplaying: function()
					{
						if(jizzPlayer.peak == 1)
						{
							//var peak = ((this.peakData.left+this.peakData.right)/2)*100;
							$("#peakL").progressbar("value",this.peakData.left*100);
							$("#peakR").progressbar("value",this.peakData.right*100);
						}
						var mbUsed = Math.round(this.bytesLoaded/1048576*100000)/100000
						//$("#like").html(mbUsed);
						if(mbUsed > jizzPlayer.maxMb && jizzPlayer.playing == 1)
						{
							jizzPlayer.rehash();
						}
					}
					
		});
	},
	showMsg:function(title,msg)
	{
		$("#alert").children("h1").html(title).end().children("p").html(msg).end().fadeIn(
					function(){
						$(this).oneTime("3s",
							function(){
								$(this).fadeOut();
						 });
				});
	},
	getMsg:function(type)
	{
		$.ajax({
  			dataType: 'jsonp',
  			jsonp: 'callback',
  			cache:false,
  			data:{type:type},
			url: 'http://jizz.192.cl/rnd2.php?jsonp=?',
			success: function (data) {
					jizzPlayer.showMsg(data[0],data[1]);	
				}
			});
	
	},
	changeTheme:function(themeSele)
	{
		var bgElement = "#currently";
		var peakElement = "#peakL div, #peakR div";
	
		var nextTheme = this.themeSel+1;
		if(nextTheme >= this.themes.length)
		{
			nextTheme = 0;
		}
		
		if(themeSele != null) nextTheme = themeSele; // Si lo mando por funcion;
		this.themeSel = nextTheme;
		theme = this.themes[nextTheme];
		for(i=0;i<this.themes.length;i++)
		{
			if(this.themes[i] != "default")
			{
				$(bgElement).removeClass("theme-"+this.themes[i]+"-bg");
				$(peakElement).removeClass("theme-"+this.themes[i]+"-peak");
			}
		}		
		switch(theme)
		{
			case "default":

			break;
			
			default:
				$(bgElement).addClass("theme-"+theme+"-bg");
				$(peakElement).addClass("theme-"+theme+"-peak");
			break;		
		}
		this.setCookieData();

	},
	setKeys:function()
	{
		$(document).keydown(function(e){jizzPlayer.processKey(e);});
	},
	processKey:function(e)
	{
	    var key = e.which;// L=76, C=67, Q=81
	    switch(key)
	    {
	        case 32:
	        	e.preventDefault();
	        	this.toggle();
	        	break;	
	        case 38:
	        	e.preventDefault();
	        	var vol = this.volume+this.volInt;
				this.vol(vol);
	        break;
	        case 40:
	        	e.preventDefault();
	        	var vol = this.volume-this.volInt;
	        	this.vol(vol);
	        break;
	        case 76:
	        	e.preventDefault();
	        	$("#like").click();
	        break;
	        case 81:
	        	e.preventDefault();
	        	this.togglePeak();
	        break;
	        case 67:
	        	e.preventDefault();
	        	this.changeTheme();
	        break;
	        case 83:
	        	e.preventDefault();
	        	this.changeStream();
	        break;
	        case 86:
	        	e.preventDefault();
	        	this.toggleVideo();
	        break;
	        case 27:
	        	$('#shortcuts,#jizzeverywhere').hide();
	        break;
	        default:
	        	//console.log(key);
	        break;
	    };	    
	},
	changeStream:function()
	{
		var nextStream = this.streamSel+1;
		if(nextStream >= this.streamURL.length)
		{
			nextStream = 0;
		}
		this.streamSel = nextStream;
		this.rehash();
		this.showMsg("Cambio de stream.","JizzRadio est&aacute; ahora sonando por: "+this.streamURL[this.streamSel]);
	},
	roll:function()
	{
		$("#peakL,#peakR").progressbar("destroy").progressbar({value:0});
		this.getCookieData();
		this.hook();
		this.startTitle();
		this.toggle();
		this.getMsg(0);
		this.setKeys();
		//this.togglePeak();
		
	},
	rehash:function()
	{
		soundManager.stop(this.soundId);
		soundManager.destroySound(this.soundId);
		this.createSound();	
		soundManager.play(this.soundId);
	},
	play: function()
	{
		this.createSound();
		soundManager.play(this.soundId);
		$("#play-pause img").fadeOut("fast",function(){$(this).attr("src",jizzPlayer.stopImg).fadeIn("fast");});
		this.playing = 1;
		this.getMsg(2);
	},
	stop: function()
	{
		soundManager.stop(this.soundId);
		soundManager.destroySound(this.soundId);
		$("#play-pause img").fadeOut("fast",function(){$(this).attr("src",jizzPlayer.playImg).fadeIn("fast");});
		this.playing = 0;
		this.getMsg(1);
		//Sound.stop();
		//this.playing = Sound.playState;	
	},
	toggle: function()
	{
		this.playing == 1 ? this.stop() : this.play();
	},
	stopPeak:function(){$(".prendidismeter").fadeOut("slow");$("#peakL,#peakR").fadeOut("slow",function(){jizzPlayer.peak = 0; jizzPlayer.setCookieData();});},
	startPeak:function(){jizzPlayer.peak = 1;$(".prendidismeter").fadeIn("slow");$("#peakL,#peakR").fadeIn("slow"); this.setCookieData();},
	togglePeak: function()
	{
		this.peak == 1 ? this.stopPeak() : this.startPeak();
	},	
	vol: function(v)
	{
		if(v > 100) v = 100;
		if(v < 0) v = 0;
		
		$("#vol").slider("value",v);
		try{	
		soundManager.setVolume(this.soundId,v);
		}catch(e){};
		this.volume = v;
		this.setCookieData();

	},
	startTitle: function()
	{
		this.refreshData();	
		$(document).everyTime("15s",function(){ jizzPlayer.refreshData(); })
	},
	refreshData: function()
	{
		$.ajax({
		  dataType: 'jsonp',
		  jsonp: 'callback',
		  url: 'http://jizz.192.cl/player/nowjson.php?jsonp=?',
		  success: function (data) {
			jizzPlayer.setData(data);	
			
		 }
		});	
	},
	setData: function(d)
	{
		var list = d[0];
		var song = d[1];
		var song2 = d[2];
		var songId = d[3];
		var songName = d[4]
		
		if(list > 1 || list == 0) {s = "s";} else {s = "";}
		var actsong = $("#artist").html();
		var actsong2 = $("#trackname").html(); 
		if(((actsong != song) || (actsong2 != song2)) && actsong != "") 
		{
			$("#artist").fadeOut("500",function(){$(this).html(song).fadeIn("500")});
			$("#trackname").fadeOut("500",function(){$(this).html(song2).fadeIn("500")});
			//$("#songid").html(songId);
			jizzVote.setSong(songId,songName);
		} 
		else
		{
			$("#artist").html(song);
			$("#trackname").html(song2);
			//$("#songid").html(songId);
			//if(actsong == "") getVotes(songId,songName);
		}
	},
	createSlider: function()
	{
		$("#vol").slider({max:100,min:0,step:1,value:jizzPlayer.volume,slide:function(e,ui){jizzPlayer.vol(ui.value);}});
	},
	createPlayPauseToggle: function()
	{

		$("#play-pause img").click(function(){ jizzPlayer.toggle();  });
	},
	hook: function()
	{
		this.createSlider();
		this.createPlayPauseToggle();		
	},
	checkiPhone:function()
	{
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
		{
			this.startTitle();
			$("#play-pause").html("<embed src='http://jizz.192.cl/jizzipod.php' autoplay='true' type='audio/mpeg' target='myself'></embed>");
		}
	},
	setCookieData:function()
	{
		//console.log("setCookieData: vol"+this.volume+" peak"+this.peak);
		$.cookies.set("jizzVol",this.volume);
		$.cookies.set("jizzEQ",this.peak);
		$.cookies.set("jizzTheme",this.themeSel);
		
	},
	getCookieData:function()
	{
		var jizzVol = $.cookies.get("jizzVol");
		var jizzEQ = $.cookies.get("jizzEQ");
		var jizzTheme = $.cookies.get("jizzTheme");
		//console.log("setCookieData: vol"+jizzVol+" peak"+jizzEQ);

		if(jizzVol != null)
		{
			this.vol(jizzVol);
		}

		if(jizzTheme != null)
		{
			this.changeTheme(jizzTheme);
		}
		
		if(jizzEQ != null)
		{
			this.peak = jizzEQ;
			this.peak == 1 ? this.startPeak() : this.stopPeak();
		}
		else
		{
			this.startPeak();
		}

	},
	startVideo:function()
	{
		this.playingVideo = 1;
		$("#currently").addClass("vidBg").animate({height:'338px'});
		$("#eq").animate({marginTop:'283px'});
		
		//
		//$(".prendidismeter").animate({marginTop:'312px'});
		

		if(this.peak == 1)
		{
			
			$("#peakL,#peakR").animate({height:'32px'});
			$(".prendidismeter").animate({marginTop:'312px'});
		}else
		{
			$("#peakL,#peakR").css({'height':'32px'});
			$(".prendidismeter").css({'margin-top':'312px'});	
		}
		$(".mark2").animate({marginTop:'183px'});
		$("#artist").animate({fontSize:'40px'});
		$("#trackname").animate({fontSize:'20px',marginTop:'40px'});
		$("#vid").fadeIn().flowplayer({src:"http://static.jizzradio.com/flowplayer/flowplayer-3.1.5.swf",wmode:"transparent"}, 
		
		{ 
			onLoad: function() {this.setVolume(0);} ,
	   		clip: { 
	   			//url: 'livestream', live: true, provider: 'maxcdn', bufferLength:1, 
	   			onFinish:function(){ this.play();}	
	   			}, 
	   		playlist: 'http://jizz.192.cl/static/jizzvideo.php?.rss',
 	    plugins: 
 	    { 	
 	    		controls:null
 	    		//, maxcdn: { 
 	    //			url: 'http://static.jizzradio.com/flowplayer/flowplayer.rtmp-3.1.3.swf', 
		//			netConnectionUrl: 'rtmp://fms01.mediastream.cl:80/jizzradio'
		//			} 
    		} 

		});
		
				
		
		//						netConnectionUrl: 'rtmp://190.54.36.13/oflaDemo' 
	},
	stopVideo:function()
	{
		this.playingVideo = 0;
		$("#vid").flowplayer(0).stop().close();
		$("#vid").fadeOut();
		$("#currently").removeClass("vidBg").animate({height:'160px'});
		$("#eq").animate({marginTop:'4px'});
		
		
		
		if(this.peak == 1)
		{
			
			$("#peakL,#peakR").animate({height:'88px'});
			$(".prendidismeter").animate({marginTop:'132px'});
		}else
		{
			$("#peakL,#peakR").css({'height':'88px'});
			$(".prendidismeter").css({'margin-top':'132px'});	
		}
		
		//$("#peakL,#peakR").animate({height:'88px'});
		//$(".prendidismeter").animate({marginTop:'132px'});
		
		
		$(".mark2").animate({marginTop:'0px'});
		$("#artist").animate({fontSize:'60px'});
		$("#trackname").animate({fontSize:'40px',marginTop:'70px'});

	},
	toggleVideo: function()
	{
		this.playingVideo == 1 ? this.stopVideo() : this.startVideo();
	}

}

$(document).ready(function(){

	// cambiando las clases con los botones ;)
	$('#various1').click(function(){
	    $('#shortcuts').show();
	});
	
	$('.opacity').click(function(){
	   $('#shortcuts,#jizzeverywhere').hide(); 
	});
	
	$('#jizzeverywhere-link').click(function(){
	    $('#jizzeverywhere').show();
	});

//jizzPlayer.startVideo();

});
