var key = '';
var flick_lev;
var volTimer;

function searchKey(w){
	key = w;
}

function search(fl){
	jQuery(document).ready(function(){
		flick_lev = fl;
		var rand = Math.floor(Math.random()*50);
	  $.ajax({
	    type: "GET",
	    url: "http://gdata.youtube.com/feeds/videos",
	    data: {
	      "vq": "music+hiphop+" + key,
	      "max-results": 1,
	      "start-index": rand,
	      "alt": "json-in-script"
	    },
	    dataType: "jsonp",
	    success: function(data) {
	      url = data.feed.entry[0].id.$t;
	      url = url.substr(38, url.length);
	      
			  $("div#myTune").empty();
				ytplayer.loadVideoById(url, parseInt(0));
	    }
	  });
	});
}


function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	ytplayer.setVolume(0);
	ytplayer.playVideo();	
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

var time = 0;
function onytplayerStateChange(newState) {
	var vol = 0;
	
	if(newState == 0){
		search(flick_lev);
	}
	else if(newState == 1){
		clearInterval(volTimer);
		if(flick_lev == 10){
			volTimer = setInterval(function(){
				if(vol == 100){
					vol = 0;
					ytplayer.setVolume(vol);
				}else{
					vol = 100;
					ytplayer.setVolume(vol);
				}
			},20);
		}else{
			volTimer = setInterval(function(){
				if(vol < 100){
					vol++;
					ytplayer.setVolume(vol);
				}else{
					clearInterval(volTimer);
				}
			},10);
		}
	}
}


