//Set some uni vars...
var videos = new Array();
var openboxarea = '';
var current_vid  = '';
var ytplayer = '';
var allvidcnt = 0;
var delhtm = '<img src="images/delete.png" alt="Remove" />';
var current_search = '';

function openbox(area) {
	if(area != openboxarea) {
	closeboxes();
	var fx = function() {
	size = $('listboxheight').value.toInt();
	overall = 26+size;
	
	$$('#'+area+' .box_small_rap').tween('height', overall);
	$$('#'+area+' .box_mid').tween('height', size);
	$$('#'+area+' .box_small_text').tween('height', size-8);
	$$('#'+area+' .box_bottom').tween('top', size+13);
	if(area != 'searchbox') {
		$$('#'+area+' .box_small_rap .openclose').set('src', 'images/close.gif');
	}
	}.delay(500);
	openboxarea = area;
	}
}
function closeboxes() {
	size = 0;
	overall = 26+size;
	$$('.box_small_rap').tween('height', overall);
	$$('.box_mid').tween('height', size);
	$$('.box_small_text').tween('height', size);
	$$('.box_bottom').tween('top', size+13);
	$$('.box_small_rap .openclose').set('src', 'images/open.gif');
}



function loadnext() {
	$$('.bottom_box .nextvideo').tween('opacity', 0.5);
}



function createbox(id, name) {

		
		var rap = new Element('div', { id: id });
		var innerrap = new Element('div', { 'class': 'box_small_rap' });
		
		var box_top = new Element('img', { 'src': 'images/box-top.gif', 'class':'box_top', 'alt':'' });
		var box_mid = new Element('img', { 'src': 'images/box-mid.gif', 'class':'box_mid', 'alt':'' });
		var box_bottom = new Element('img', { 'src': 'images/box-bottom.gif', 'class':'box_bottom', 'alt':'' });
	
	
	
}

        function onPlayerError(errorCode) {
          /*alert("An error occured: " + errorCode);*/
        }



    function onYouTubePlayerReady(playerId) {
		//Find the video player
		ytplayer = document.getElementById('myytplayer');
		//Add events when player chagnes status
		ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
		ytplayer.addEventListener("onError", "onPlayerError");
		ytplayer.playVideo();
    }


window.addEvent('domready', function() {
	$$('#playlist .box_small_rap h2, #playlist .box_small_rap .openclose').addEvent('click', function() {
		openbox('playlist');
	});	
	$$('#related .box_small_rap h2, #related .box_small_rap .openclose').addEvent('click', function() {
		openbox('related');
	});
	$$('#featured .box_small_rap h2, #featured .box_small_rap .openclose').addEvent('click', function() {
		openbox('featured');
	});
	$$('#searchbox .box_small_rap .openclose').addEvent('click', function() {
		search();
	});
	
	
	
	$$('#searchbox .box_small_rap h2').addEvent('click', function() {
	
		$('keywords').focus();
	});
	
	
	


	startvid = (window.location.hash) ? window.location.hash.replace(/#/, '') : 'DFM140rju4k';

	loadvideo(startvid);

		
	openbox('featured');
});



function onytplayerStateChange(newState) {
//alert(newState);

//Load Next Video
	if(newState == 0) {
		for(i=0; i<videos.length; i++) {
		
			if(videos[i] == current_vid) {
				if(videos[(i+1)]) {
				current_vid = videos[(i+1)];
			
				loadvideo(current_vid);
				
			
			return false;
			}
			}
		
	

}
	}
}



function videoRow(jsonVideos, area) {
	allvids = new Array();
	jsonVideos = jsonVideos.details;
	area.set('html', '');
	jsonVideos.each(function(ele) {
		
		rap = new Element('div');
		
		innerrap = new Element('div', {'styles': {'position': 'relative'}, 'id': 'video_'+ele.vidid}).addClass("a"+ele.vidid);
		thumb = new Element('img', {'src': ele.thumb, 'class': 'thumb', 'align': 'left'});
		vidtitle = new Element('h3');
		
		titleh3 = new Element('h3')
		titlelink = new Element('a', {'href': 'javascript:;', 'title': 'Play Video'}).set('text', ele.title);
		titlelink.set('onclick', 'loadvideo("'+ele.vidid+'")');
		
	
		
		authorlink = new Element('a').set('text', ele.author);
		divclear = new Element('div', {'class': 'clear'});
		divclear2 = new Element('div', {'class': 'clear'});
		
		
		playbtn = new Element('a', {'href': 'javascript:;', 'title': 'Play Video', 'class': 'btnplay'}).set('onclick', 'loadvideo("'+ele.vidid+'");').set('html', '<img src="images/play.png" align="left" alt="Play Video" />');
	
		addbtn = new Element('a', {'href': 'javascript:;', 'title': 'Add Video to Playlist', 'class': 'btnadd'}).set('onclick', 'addVideo("'+ele.vidid+'")').set('html','<img src="images/add.png" align="left" alt="Add video to playlist" />');
		hr = new Element('hr');
		
		
		
		//Put it all together
		innerrap.inject(rap);
		titlelink.inject(vidtitle);
		
		
		
		thumb.inject(innerrap);
		titlelink.inject(titleh3);
		titleh3.inject(innerrap);
		
		innerrap.set('html', innerrap.get('html')+ele.viewCount+'<br />');
		
		authorlink.inject(innerrap);
		divclear.inject(innerrap);
		
		playbtn.inject(innerrap);
		addbtn.inject(innerrap);
		divclear2.inject(innerrap);
		hr.inject(innerrap);
		
		allvids.push(innerrap);
		area.adopt(innerrap);
		
		if(videos.contains(ele.vidid)) {
			$$('.a'+ele.vidid+' .btnadd').each(function(fele) { fele.set('html', delhtm).set('title', 'Remove from playlist').set('onclick', 'removevideo("'+ele.vidid+'");'); });
		}

		
	});
	
	
	
}


function addVideo(vidid) {
	videos.push(vidid);
	allvidcnt++;
	
	$('playcount').set('html', videos.length);
	
	var vid = $('video_'+vidid).get('html');
	var exist = $$('#playlist .box_small_text').get('html');
	$$('#playlist .box_small_text').set('html', exist+'<div style="position: relative;" id="video_playlist_'+vidid+'" class="a'+vidid+'">'+vid+'</div>');
	
	
	$$('.a'+vidid+' .btnadd').each(function(fele) { fele.set('html', delhtm).set('title', 'Remove from playlist').set('onclick', 'removevideo("'+vidid+'");'); });
	
		

	
	
}


function removevideo(vidid) {

			$('video_playlist_'+vidid).destroy();
			videos.erase(vidid);
	

			$$('.a'+vidid+' .btnadd').set('html', '<img src="images/add.png" alt="Add" />').set('title', 'Add video to playlist').set('onclick', 'addVideo("'+vidid+'")');

	
	videos.clean();
	$('playcount').set('html', videos.length);
	
}





function loadvideo(vidid) {

		//$('ytapiplayer').clearVideo(); 
		//$('ytapiplayer').loadVideoById(vidid, parseInt(0));
		window.location = '#'+vidid;
		
					
			$('videodiv').set('html', '<div id="ytapiplayer"></div>');		
	var params = { allowScriptAccess: "always", bgcolor: "#cccccc"};
      // this sets the id of the object or embed tag to 'myytplayer'.
      // You then use this id to access the swf and make calls to the player API
      var atts = { id: "myytplayer" };
      swfobject.embedSWF("http://www.youtube.com/v/"+vidid+"&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer",
                         "ytapiplayer", "642", "385", "8", null, null, params, atts);

					
					
					
					
		
		current_vid = vidid;
		var req = new Request.HTML({url:'get.php', onSuccess: function(bla, ele, htel) { $$('.bottom_box').set('html', htel); } }).get({'action': 'details', 'video_id': vidid});
		
		$$('#related .box_small_rap .openclose').set('src', 'images/load.gif');
		var req = new Request.JSON({url:'get.php', onSuccess: function(jsnvids) { videoRow(jsnvids, $$('#related .box_small_text')); $$('#related .box_small_rap .openclose').set('src', 'images/open.gif');  } }).get({'action': 'Related', 'video_id': vidid});
	
}



function search() {
	openbox('searchbox');
	words = $('keywords').get('value');
	
	
	if(words != current_search) {
		$$('#searchbox .box_small_rap .openclose').set('src', 'images/load.gif');
		current_search = words;
		var fx = function() {$$('#searchbox .box_small_text').tween('opacity', 0);
		
		var req = new Request.JSON({url:'get.php', onSuccess: function(jsnvids) {  videoRow(jsnvids, $$('#searchbox .box_small_text'));  $$('#searchbox .box_small_text').tween('opacity', 1); $$('#searchbox .box_small_rap .openclose').set('src', 'images/close.gif'); } }).get({'action': 'search', 'video_id': words});
	
		}.delay(1500);
	}
}


