var normalplayer = false;
var start = true;  
var newState;  
var timer;
var repeat = 0; //repeat the current song - 1
var playerState = -1;  // unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5).   
var normalplayer = false;
var currentid = 0;
var currenttitle = 0;
var playerSize = 2; //large - 1  small - 2
var idleTime = 50000; //idle time before fullscreen mode
var timeOut;

var LOADER_WIDTH = 300; //width or progress bar for loading music  
var OFFSET = 412; //mouse offset width	
var AUDIO_WIDTH = 100; //width or progress bar for loading music  
var AUDIO_OFFSET = 615; //mouse offset width	
var RESULTS_PER_PAGE = 16; // max number of video search and video results - 1
var MAX_LEN = 40; //max length of text in top display  

if(isIE()){
	var MAX_TITLE_LEN = 34; //max length of text in top display  
}else{
	var MAX_TITLE_LEN = 36;
}

var currentList = 'ul1';
var resultsPerPage = RESULTS_PER_PAGE;
var queryType;

var TABS = ['search', 'related', 'played', 'recommend', 'popular'];

function recommendVideos(){	
	var list = $("ul4");	
	var items = list.getElementsByTagName("li");		
	
	if(items.length > 0) 
			clearList('ul1');		
	
	for(var i=0;i<Math.min(items.length);i++){
		ytsearch(items[i].id, "recommended", 0);
	}
	
	var items = list.getElementsByTagName("li");
	
	if(items.length == 0){
		ytsearch('', 'related', 0);
	}	
				
}

function getMusicRecommendations(){
	clearList("ul1");
	unselectTabs();
	selectTab(TABS[3]);
	
	if(currentid == 0){	
		showMessageBox('No Video Is Playing');		
	}else if(getArtist() != "" && getTrack() != ""){			
		//alert(getArtist() + "-"  + getTrack());
		//new Ajax.Updater({success:'ul4',failure:'ul4'}, '/music/recommend?track=' + getTrack().gsub(" ","_") + '&artist=' + getArtist().gsub(" ","_"), {asynchronous:true, evalScripts:true, onComplete:function(request){Element.hide('loader'); recommendVideos();}, onLoading:function(request){Element.show('loader')}});
		ytsearch('', 'related', 0); //Artist or Track Could Not Be Found so get related videos
	}else{		
		ytsearch('', 'related', 0); //Artist or Track Could Not Be Found so get related videos
		showMessageBox('Artist or Track Could Not Be Found');
	}
}

function getMostPopular(){
	clearList('ul1');
	unselectTabs();
	selectTab(TABS[4]);	
	loadInitVideos();
}

function loadInitVideos(){
	var list = $('ul5');
	var items = list.getElementsByTagName("li");
	var currentList = "ul1";
	
	for(i=0;i<items.length;i++){
	
		var videoid = items[i].id;
		var title = items[i].innerHTML;
		
		if(isIE()){
			addListElement('<a href="#v='+ videoid +'" onclick="javascript:playVideo(\'' + videoid + '\',\'' + title + '\'); return false;"><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title,currentList);
		}else{
			addListElement('<a href=\'#v=' + videoid + '\'><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title, currentList);
		}			
		
	}
}

function getSimilarArtists(){
	ytsearch('','artist',0, 'ul1');
}

function appendScriptTag(scriptSrc, scriptId, scriptCallback) {
	
	// Remove any old existance of a script tag by the same name	
	scriptId += currentList;
	
	if(resultsPerPage == 1)
		scriptId = scriptId + Math.random()*1000;
			
	var oldScriptTag = document.getElementById(scriptId);
	if (oldScriptTag) {
		oldScriptTag.parentNode.removeChild(oldScriptTag);
	}
	// Create new script tag
	var script = document.createElement('script');
	script.setAttribute('src', scriptSrc + '&alt=json-in-script&callback=' + scriptCallback);
	script.setAttribute('id', scriptId);
	script.setAttribute('type', 'text/javascript');
	document.getElementsByTagName('head')[0].appendChild(script);
}

function getVideoId(url){
	var match = url.indexOf('=');
	if (match) {
	 videoid = url.substring(match +1, match + 12);
	 return videoid;
	}
}

function getId(string){		
	var match = string.lastIndexOf("'s Videos");
	if (match != -1) {
		id = string.substring(0,match);
		return id.toLowerCase();
	}
	var match = string.lastIndexOf("query");
	if (match != -1) {
		id = string.substring(match+7);
		return id.toLowerCase();
	}	
}


function listVideos(json, query, queryType, startIndex, totalResults) {
	var numVideos = 0;
	
	query = encodeURI(query);
	
	hideLoader();

	if(json.feed.entry){
		for (var i = 0; i < json.feed.entry.length; i++) {
			var entry = json.feed.entry[i];

			for (var k = 0; k < entry.link.length; k++) {
				if (entry.link[k].rel == 'alternate') {
					url = entry.link[k].href;
					break;
				}
			}

			//remove videos that disable embeds		
			var title = entry.title.$t;				
			var noembed = entry['yt$noembed'];				
			var thumb = entry['media$group']['media$thumbnail'][1].url.gsub("1.jpg","default.jpg");
			var viewCount = entry['yt$statistics']['viewCount'];
			var favoriteCount = entry['yt$statistics']['favoriteCount'];
			var rating = entry['gd$rating']['average'];
			var numRaters = entry['gd$rating']['numRaters'];								
			var videoid = getVideoId(url);	
			var title = addslashes(entry.title.$t);									
				
			if(badStats(title, noembed, viewCount, favoriteCount, rating, numRaters) != true && numVideos < resultsPerPage){	   		
				numVideos++;
								
				if(isIE()){
					addListElement('<a title="' + videoid + '" href="#v='+ videoid +'" onclick="javascript:playVideo(\'' + videoid + '\',\'' + title + '\'); return false;"><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title,currentList);
				}else{
					addListElement('<a title="' + videoid + '" href=\'#v=' + videoid + '\'><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title, currentList);
				}
					
			}				
		}
				
		if(resultsPerPage != 1 && currentList == 'ul1'){ //recommendations displays 1 video per search. Don't show pagination			
		//remove videos 
		for(m=0;m<Number(numVideos % 4);m++){
			removeListElement(currentList);
		}				
		
		// add pagination
		var page = Math.floor(startIndex/RESULTS_PER_PAGE);		
		var numPrev = 0;
		var list = $(currentList);	
		var nextprev = document.createElement('li');

		var styleData = 'width:450px;font-size:14px;height:30px; font-weight:bold;color:#CBCED1;letter-spacing:-0.05em;'	

		if(!isIE()){
			nextprev.setAttribute('style', styleData + "margin-top:10px;"); //use the correct DOM Method
		} else {
			nextprev.style.setAttribute('cssText', styleData + "width:460px;"); //use the .cssText hack		    
		}

		if(page > 0){
			nextprev.innerHTML += '<a href=javascript:ytsearch(\'' + query + '\',\'' + queryType + '\',' + (page-1) + ',\'ul1\')>&larr; Prev</a>&nbsp;&nbsp;';				
		}	
		
		for(var p=page-4;p<page;p++){
			if(p >= 0){
				nextprev.innerHTML += '<a href=javascript:ytsearch(\'' + query + '\',\'' + queryType+'\',' + (p) + ',\'ul1\')> ' + (p+1) + ' </a>';		
				numPrev++;
			}	
		}
									
		nextprev.innerHTML += "<span style='text-decoration:underline;'>" + (page + 1) + "</span>";		
		
		for(var p=page+1;p<page+(10 - numPrev);p++){
			if(Number(totalResults) > ((p+1) * Number(RESULTS_PER_PAGE)))		
				nextprev.innerHTML += '<a href=javascript:ytsearch(\'' + query + '\',\'' + queryType+'\',' + (p+1) + ',\'ul1\')> ' + (p+1) + ' </a>';						
		}
			
		if(Number(totalResults) > (Number(startIndex) + Number(RESULTS_PER_PAGE))){			
			nextprev.innerHTML += '&nbsp;&nbsp;<a href=javascript:ytsearch(\'' + query + '\',\'' + queryType+'\',' + (page+1) + ',\'ul1\')>Next &rarr;</a>';	
		}
		
		list.appendChild(nextprev);	
		}
	}else{			
		if(resultsPerPage != 1 && currentList == 'ul1') showMessageBox('No Results Found')
	}

}


function badStats(title, noembed, viewCount, favoriteCount, rating, numRaters){
	if(title.match(eval("/(cover|remake|kareoke|karaoke|acoustic|singing|videoke|instrumental|interview|alvin|chipmunks|chipmunk|keyboard|re:|request)/i"))
	|| title.match(eval("/(sex|sexy|milf|xxx|webcam)/i"))
	|| title.match(eval("/(me).*(singing)/i"))
	|| favoriteCount < 20
	|| noembed != null 
	){	
		return true;
	}else{			
		return false;
	}
}

function youtubeEntryInit(root){
	var title = root.entry.title.$t;
	var url = root.entry.id.$t;
	var vid = url.split("videos/")[1];

	currenttitle = title;		
	updateTitles(title);
	updateVideo(vid, stripslashes(title));

}

function youtubeInit(root) {
	
	//this hacks the layer for mutiple json queries
	id = getId(root.feed.title.$t);	
	var type = queryType;
	
	var query = "";
	if(root.feed.title.$t.match("query"))
		query = root.feed.title.$t.split(": ")[1]

	if(root.feed.title.$t.match("related")){
		queryType = "related";
	}else if(root.feed.title.$t.match("query")){
		queryType = "search";
		query = root.feed.title.$t.split(": ")[1]
	}else{
		queryType = "search";
	}
	
	var totalResults = root.feed['openSearch$totalResults'].$t;	
	var startIndex = root.feed['openSearch$startIndex'].$t;
	
	listVideos(root, query, queryType, startIndex, totalResults);	  
}


/* -----------------------------------
* Functions for playing videos 
* ----------------------------------- */

function getVideoAndPlay(id){
	var url = 'http://gdata.youtube.com/feeds/api/videos/' + id + '?';
	playNewVideo(id);
	appendScriptTag(url, 'scriptId2', 'youtubeEntryInit');
}

function playVideo(id, title){				
	id = id.split('|')[0];						
	playNewVideo(id);		
	updateTitles(title);					
	saveHistory(id, title);
}

function playNewVideo(id){
	selectVideo(id); //highlight the video(s) being played
	unselectVideos(); //unhighlight all videos					
	loadNewVideo(id);
	//ytsearch('','related',0,'ul3');							
}

//similar to getVideoAndPlay but loads related into UL1 not UL3
function getStartVideo(id){
	var url = 'http://gdata.youtube.com/feeds/api/videos/' + id + '?';
	selectVideo(id); //highlight the video(s) being played
	unselectVideos(); //unhighlight all videos					
	loadNewVideo(id);
	appendScriptTag(url, 'scriptId2', 'youtubeEntryInit');
	ytsearch('','related',0, 'ul1');
}

function updateTitles(title){
	currenttitle = title;	//used by the status bar		
	if(document.title) document.title = stripslashes(title) + " - musicnow.fm"; //update the title
	$('status').innerHTML = stripslashes(title).truncate(MAX_TITLE_LEN);			
}

function updateVideo(id, title){
	id = id.split('|')[0];
	var title = stripslashes(title);				
	updateTitles(title);		
	saveHistory(id, title);		
}

function getTitle(){		
	var artist = getArtist();
	var track = getTrack();	
	title = artist + "-" + track;	
	title = title.gsub(" ","_");	
	return title;
}

function getCleanTitle(){
	var title = currenttitle;
	title = title.gsub("\'", "");
	title = title.gsub("\"", "");
	title = title.gsub(eval("/(official|video|uncensored|music|remix|rmx)/i"), '');
	title = title.gsub("\\(.*\\)", '');
	title = title.gsub("\\*.*\\*", '');
	return title;
}

function getArtist(){
	
	var artist = "";
	var title = getCleanTitle();
	
	var temp  = title.gsub(eval("/(ft|feat)[.]*.*/i"), '');
	var temp2 = title.gsub(eval("/(jay-z|j-shin|t-pain|ne-yo)/i"), '');
	
	if(temp2.split("-").length > 1){								
		var artist = temp.substring(0, title.lastIndexOf("-"));				
	}else{						
		artist = temp.split(" ")[0];		
		if(title.split(" ").length > 2)
			artist += " " + temp.split(" ")[1];									
	}	

	artist = artist.split(",")[0];
	artist = artist.split("&")[0];	
	artist = artist.split(" -")[0];
	artist = artist.split("- ")[0];			
	artist = artist.gsub(eval("/(\\[|\\(|\\{).*/i"),"");		
	artist = artist.gsub(eval("/(ft|feat).[.]*.*/i"), '');
	artist.gsub("-", " ");	

	return artist;		
}


function getTrack(){
	var title = getCleanTitle();
	
	var temp  = title.gsub(eval("/(ft|feat)[.]*.*/i"), '');
	var temp2 = title.gsub(eval("/(jay-z|j-shin|t-pain|ne-yo)/i"), '');
	
	if(temp2.split("-").length > 1){								
		var track =  temp2.split("-")[1]; //temp.substring(title.lastIndexOf("-") + 1, title.length);									
	}else{
				
		var artist = temp.split(" ")[0];		
		if(title.split(" ").length > 2)
			artist += " " + temp.split(" ")[1];							
		track = title.gsub(eval("/(ft|feat)[.]*/i"), '').substring(artist.length+1, title.length);

	}	

	track = track.gsub(eval("/(\\[|\\(|\\{).*/i"), '');			
	track = track.gsub(eval("/(ft|feat)[.]*.*/i"), '');
	track.gsub("-"," ");	
	return track;	
}

/* -----------------------------------
* Performs a YT search API request 
* ----------------------------------- */

function youtubeAPIRequest(type,q,maxResults,page, list){
	
	currentList = list;
	
	var startIndex = (page * RESULTS_PER_PAGE) + 1;	  

	var htmlTitle = "";

	var script = document.createElement('script');
	var url = "http://gdata.youtube.com/feeds/api";

	switch(type){

		case "search":
		url += '/videos?vq='+q+'&start-index='+startIndex+'&max-results='+maxResults+'&category=Music';						
		htmlTitle = q.gsub("%20", " ");
		break;
		
		case "recommended":
		url += '/videos?vq='+q+'&start-index='+startIndex+'&max-results='+maxResults+'&category=Music';						
		htmlTitle = q.gsub("%20", " ");
		break;

		case "related":	    
		url += '/videos/' + q + '/related?start-index='+startIndex+'&max-results='+maxResults;						
		htmlTitle = "Related Videos";	
		break;

		case "featured":
		url += '/standardfeeds/recently_featured?start-index=1&max-results=50';
		htmlTitle = "Recently Featured";
		break;

		case "mostpopular":
		url += '/standardfeeds/most_popular?category=Music&start-index=1&max-results=50';
		htmlTitle = "Most Popular";
		break;

		case "mostviewed":
		url += '/standardfeeds/most_viewed?category=Music&time=all_time&start-index=1&max-results=50';
		htmlTitle = "Most Popular";
		break;

		default:
		url += '/standardfeeds/most_viewed?category=Music&time=all_time&start-index=1&max-results=50';
		htmlTitle = "Most Popular";
	}

	if(document.title)
		document.title = htmlTitle + "- musicnow.fm";
	appendScriptTag(url, 'scriptId', 'youtubeInit');
}


/* -----------------------------------
* Format song titles  
* ----------------------------------- */
function addslashes(str) {
	str=str.replace(/\'/g,'\'');
	str=str.replace(/\"/g,'');
	str=str.split(" ").join("&nbsp;");
	return str;
}

function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.split("&nbsp;").join(" ");		
	return str;
}


/* -----------------------------------
* Yahoo YUI Drag and Drop  
* ----------------------------------- */
(function() {

	var Dom = YAHOO.util.Dom;
	var Event = YAHOO.util.Event;
	var DDM = YAHOO.util.DragDropMgr;


	YAHOO.example.DDApp = {
		init: function() {


			for(var c=1;c<4;c++){
				new YAHOO.util.DDTarget("ul" + c);				
			}

			for(var r=1;r<4;r++){				
				var ul = $('ul' + r);
				var nodes = ul.getElementsByTagName("li");			

				for(i=0;i<nodes.length;i=i+1){
					new YAHOO.example.DDList(nodes[i].id);												
				}

			}
		
		}
		
	};

	YAHOO.example.DDList = function(id, sGroup, config) {

		YAHOO.example.DDList.superclass.constructor.call(this, id, sGroup, config);

		this.logger = this.logger || YAHOO;
		var el = this.getDragEl();
		Dom.setStyle(el, "opacity", 0.67); // This is slightly transparent

		this.goingUp = false;
		this.lastY = 0;
		this.lastX = 0;
	};

	YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {

		startDrag: function(x, y) {

			// make the proxy look like the source element
			var dragEl = this.getDragEl();
			var clickEl = this.getEl();
			Dom.setStyle(clickEl, "visibility", "hidden");

			dragEl.innerHTML = clickEl.innerHTML;

			Dom.setStyle(dragEl, "color", Dom.getStyle(clickEl, "color"));
			Dom.setStyle(dragEl, "backgroundColor", Dom.getStyle(clickEl, "backgroundColor"));
			Dom.setStyle(dragEl, "border", "none");
		},

		endDrag: function(e) {

			var srcEl = this.getEl();
			var proxy = this.getDragEl();

			// Show the proxy element and animate it to the src element's location
			Dom.setStyle(proxy, "visibility", "");
			var a = new YAHOO.util.Motion( 
				proxy, { 
					points: { 
						to: Dom.getXY(srcEl)
					}
				}, 
				0.2, 
				YAHOO.util.Easing.easeOut 
			)
			var proxyid = proxy.id;
			var thisid = this.id;

			// Hide the proxy and show the source element when finished with the animation
			a.onComplete.subscribe(function() {
				Dom.setStyle(proxyid, "visibility", "hidden");
				Dom.setStyle(thisid, "visibility", "");
			});
			a.animate();
			savePlaylist();
		},
				
		onDragDrop: function(e, id) {

			  // If there is one drop interaction, the li was dropped either on the list,
		        // or it was dropped on the current location of the source element.
		        if (DDM.interactionInfo.drop.length === 1) {
		            // The position of the cursor at the time of the drop (YAHOO.util.Point)
		            var pt = DDM.interactionInfo.point; 
		            // The region occupied by the source element at the time of the drop
		            var region = DDM.interactionInfo.sourceRegion; 
		
					if (!region.intersect(pt)) {		               
		            	var destEl = Dom.get(id);
		                var destDD = DDM.getDDById(id);
		                destEl.appendChild(this.getEl());
		                destDD.isEmpty = false;
		                DDM.refreshCache();
						savePlaylist();
		            }														
					
		        }
		},

		onDrag: function(e) {
			// Keep track of the direction of the drag for use during onDragOver
			var y = Event.getPageX(e);

			if (y < this.lastY) {
				this.goingUp = false;
			} else if (y > this.lastY) {
				this.goingUp = true;
			} 

			this.lastY = y;
		}, 

		onDragOver: function(e, id) {

			var srcEl = this.getEl();
			var destEl = Dom.get(id);

			// We are only concerned with list items, we ignore the dragover
			// notifications for the list.
			if (destEl.nodeName.toLowerCase() == "li") {
				var orig_p = srcEl.parentNode;
				var p = destEl.parentNode;

				if (this.goingUp) {
					p.insertBefore(srcEl, destEl); // insert above
				} else {
					p.insertBefore(srcEl, destEl.nextSibling); // insert below
				}

				DDM.refreshCache();
			}
		}
	});


})();


/* -----------------------------------
* Plays the next song in a playlist 
* or search result if the playlist
* is empty 
* ----------------------------------- */

function getNextPlaylist(){

	if(repeat == 1 && currentid) { //check if the video setting is on repeat
		getVideoAndPlay(currentid);
	}else{

		var playlistplay = 0;

		for(j=2;j>0;j--){
			var items = $("ul" + j).getElementsByTagName("li");	
			for (i=0;i<items.length;i=i+1) {
				if( items[i].id.split("|")[0] == currentid && playlistplay == 0){						

					var p=Number((i+1) % items.length);
					if(items[p]){
						playlistplay = 1;													
						getVideoAndPlay(items[p].id.split("|")[0]);
						break;
					}
				}
			}

		}
		
		if(playlistplay == 0 && items.length > 0)
			getVideoAndPlay(items[0].id.split("|")[0]);			

	}	
}

function getPrevPlaylist(){

	var playlistplay = 0;

	for(j=2;j>0;j--){			
		var items = $("ul"+j).getElementsByTagName("li");	

		for (i=0;i<items.length;i=i+1) {
			if(items[i].id.split("|")[0] == currentid && playlistplay == 0){
				var p = i-1;
				if(p < 0) p = Number(items.length - 1);																
				if(items[p]){
					playlistplay = 1;
					getVideoAndPlay(items[p].id.split("|")[0]);	
					break				
				}
			}
		}
	}

	if(playlistplay == 0 && items.length > 0)
		getVideoAndPlay(items[0].id.split("|")[0]);
}

function addListElement(text,id,title,ul){
	try
	{
		if(text && id && ul){
			var list = document.getElementById(ul);
			var newNode = document.createElement("li");
			newNode.setAttribute('id',id + '|' + ul);
			newNode.setAttribute('name',title);
			newNode.innerHTML = text;				
			list.appendChild(newNode);
			if(YAHOO.example && newNode != 'null')
			new YAHOO.example.DDList(newNode);
		}
	}
	catch(err)
	{
		//Handle errors here
	}

}

function removeListElement(ul){
	var list = $(ul);
	list.removeChild(list.lastChild);
}

/* -----------------------------------
* Removes all videos from a UL element
* ----------------------------------- */

function clearList(ul){

	var list = $(ul);
	while (list.firstChild) 
	{
		list.removeChild(list.firstChild);
	}
	if(ul == "ul2")	
	$('dragAndDrop').show();	
}


/* -----------------------------------
* Selects a tab in the videos box 
* ----------------------------------- */

function selectTab(tab){
	for(i=0; i<TABS.length; i++){					
		if(TABS[i] == tab){
			$(TABS[i]).className = "headerItem selected";
		}else{
			$(TABS[i]).className = "headerItem";
		}
	}
}

function unselectTabs(){
	selectTab("");
	hideMessageBox();
}

function initSearch(){	
	
	currentList = 'ul1';
	clearList(currentList);
	
	if(document.URL.match("v=")){
		videoid = document.URL.split("v=")[1];									
		getStartVideo(videoid);		
	}else{			
		if(getCookie('history') == "" || getCookie('history') == null){									
			//ytsearch('rihanna','search',0, currentList);
			loadInitVideos();
		}else{
			//loadInitVideos();
			createTopPlayed();
		}	
	}
}

/* -----------------------------------
* Retrieve search results or related videos 
* ----------------------------------- */
function getSearchQuery(){
	return encodeURI($('searchinput').value);
}


function ytsearch(query, type, page, list){
		
	query = decodeUrl(query);
	
	if(list == null){
		currentList = "ul1";
	}else{
		currentList = list;
	}
	
	clearList(currentList);	
	unselectTabs();
	
	switch(type)
	{

		case 'search':	
			//selectTab(TABS[0]);		
										
			if(query == "Enter Song or Artist..." || query == ""){ 
				showMessageBox('Search Box Is Empty');
				query = "";	
			}
			
			if(query == "")	return;
				
			resultsPerPage = RESULTS_PER_PAGE;			
			var maxResults = resultsPerPage + 25;	
			
			break;

		case 'artist':	
			
			selectTab(TABS[1]);
									
			if(currentid == 0)
				showMessageBox('No Video Is Playing');
			
			var query = getArtist();
			
			if(query == ""){
				var query = getVid();
				type = "related";					
			}else{
				type = "search";
			}
						
			resultsPerPage = RESULTS_PER_PAGE;			
			var maxResults = resultsPerPage + 25;					
			break;
		
		case 'related':				
			//selectTab(TABS[3]);	
			
			if(currentid == 0)
				showMessageBox('No Video Is Playing');
					
			var query = getVid();									
			
			if(currentList == 'ul3'){				
				resultsPerPage = 12;			
				var maxResults = resultsPerPage + 10;				
			}else{
				resultsPerPage = RESULTS_PER_PAGE;			
				var maxResults = resultsPerPage + 25;								
			}
			break;
		
		case 'recommended':				
			resultsPerPage = 1;
			var maxResults = resultsPerPage + 5;
			break;	
								
	}
				
	showLoader();
	youtubeAPIRequest(type,query,maxResults, page, currentList);	
		
}

/* -----------------------------------
* Deletes or saves cookies 
* ----------------------------------- */

function setCookie(name, value, expires, path, domain, secure)
{
	document.cookie= name + "=" + escape(value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1)
	{
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	}
	else
	{
		begin += 2;
	}
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
	{
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
}

function deleteCookie(name, path, domain)
{
	if (getCookie(name))
	{
		document.cookie = name + "=" + 
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		"; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

/* -----------------------------------
* Writes each video play to the history 
* cookie with a max of 100 views 
* Format: |videoid,title|videoid2,title2 
* ----------------------------------- */

function saveHistory(id, title){

	var id = id.split("|")[0];		  	
	var title = stripslashes(title).truncate(MAX_LEN);

	var new_history = getCookie('history');				

	if(new_history != null && new_history != ""){
		new_history += id + "=" + title + "|";
	}else{
		new_history = id + "=" + title + "|";
	}	

	var items = new_history.split("|");

	if(items.length > 20){
		items = items.splice(2,items.length-1);
		new_history = items.join("|")
	}																											
	var time = new Date("Jan 1, 2010 01:00:00"); 								
	setCookie('history',new_history,time); 

}



/* -----------------------------------
* Sorts the videos in the cookie history 
* by frequency 
* ----------------------------------- */
function sortByViews(a, b) {
	var x = Number(a.split("=")[2]);
	var y = Number(b.split("=")[2]);
	return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function getTopPlayed(){
	unselectTabs();
	var history = getCookie('history');
	var items = history.split('|');

	var freq = new Array();
	var found = 0;

	for(var i=0;i<items.length-1;i++){
		var id = items[i].split("=")[0];
		var title = items[i].split("=")[1];

		for(var j=0;j<freq.length;j++){
			if(freq[j].split("=")[0] == id){
				var count = Number(freq[j].split("=")[2]);					
				freq[j] = id + "=" + title + "=" + String(Math.min(count + 1, 11));
				found = 1;					
			}
		}

		if(found == 0){
			freq[freq.length] = id + "=" + title + "=" + "1";
		}	

		found = 0;	
	}

	var sorted = freq.sort(sortByViews);
	sorted = sorted.join("|");
	return sorted;
}

/* -----------------------------------
* Displays a list of videos from a cookie 
* Format: |videoid,title|videoid2,title2 
* ----------------------------------- */

function createFromCookie(type){			
				
	switch(type)
	{
		case "history":							
		var list = getTopPlayed();				
		var ul = "ul1";
		selectTab("played");
		if (list!="" || list!=null){		
			clearList(ul);
		}														
		break;

		case "playlist":
		var list = getCookie('playlist');
		var ul = "ul2";

		if (list=="" || list==null){		
			$('dragAndDrop').show();
		}else{
			$('dragAndDrop').hide();
		}
		break;					
	}


	if (list!="" || list!=null){				    
		var vid_array=list.split('|');
		var part_num=0;

		while (part_num < vid_array.length)
		{

			if(vid_array[part_num]=='' || vid_array[part_num]=='null'){

			}else{
					
				var videoid = vid_array[part_num].split("=")[0];
				var title = addslashes(vid_array[part_num].split("=")[1]);
				
				if(isIE()){
					addListElement('<a href="#v=' + videoid + '" onclick="javascript:playVideo(\'' + videoid + '\',\'' + title + '\'); return false; "><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title,ul);
				}else{
					addListElement('<a href=\'#v=' + videoid + '\'><img src="http://img.youtube.com/vi/'+videoid+'/2.jpg" title="'+title+'"><br />' + stripslashes(title).truncate(MAX_TITLE_LEN) + '</a>',videoid, title,ul);
				}																				
			}	
			part_num+=1;
		}			
	}
}	


function createTopPlayed(){			
	//check for any videos in the history cookie
	if(getCookie('history') == "" || getCookie('history') == null){
		clearList("ul1");
		showMessageBox('No videos have been played yet');
	}else{
		
		if(getCookie('history').match("@")){
			var new_history = getCookie('history').gsub("@","="); 
			var time = new Date("July 21, 2009 01:00:00");
			setCookie('history',history,time);
		}		
		createFromCookie('history');
	}

}	

function createPlaylist(){
	createFromCookie("playlist");
}

function savePlaylist(){	
	$('dragAndDrop').hide();			
	ul = $('ul2');
	var items = ul.getElementsByTagName("li");
	var new_playlist = "";	
	
	if(items.length != 0){
				  
	for (var i=0;i<items.length;i=i+1) {
		var title = String(items[i].attributes["name"].value).gsub(eval("/\"/"), "");
		new_playlist += items[i].id.split('|')[0] + "=" + title  + "|";
	}

		var time = new Date("July 21, 2009 01:00:00");
		setCookie('playlist',new_playlist,time);
	}
}

function removeVideo(id){
	var list = getCookie('playlist');

	if (list!="" || list!=null){				    
		var vid_array=list.split('|');
		var part_num=0;

		while (part_num < vid_array.length)
		{

			if(vid_array[part_num]=='' || vid_array[part_num]=='null'){

			}else{
				var videoid = vid_array[part_num].split("=")[0];
				
				if(id == videoid){
					
				}
					
			}
		}
	}			
}

/* -----------------------------------
* Deletes the playlist and history cookies 
* ----------------------------------- */

function clearCookie(type){

	switch(type){

		case "playlist":
		deleteCookie('playlist');
		clearList('ul2');
		break;

		case "history":
		deleteCookie('history');
		selectTab(TABS[2]);
		clearList('ul1');
		break;			
	}
}

function clearPlaylist(){
	clearCookie("playlist");
}

function clearHistory(){
	clearCookie("history");
}

//YAHOO.util.Event.onDOMReady(initSearch);
YAHOO.util.Event.onDOMReady(createPlaylist);

function selectSearchbox(){
	var searchField = $('searchinput');	
	searchField.focus();
}	

//encode a url
function encodeUrl(url) {
	return escape(url);
}
//decode a url (remove the %'s etc)
function decodeUrl(url) {
	url = url.gsub("%20", " ");
	url = url.gsub("\'","");
	return url;
	//return unescape(url.replace("/\+/g",  " "));
}	

function updateHTML(elmId, value) {
	$(elmId).innerHTML = value;
}


function setNormalPlayerState(newState) {    
	playerState = newState;
	title = currenttitle;

	switch(newState)
	{
		case -1:
		updateHTML('status', 'musicnow.fm - stream music videos');
		break;    

		case 0:
		updateHTML('status', ('Stopped - ' + title).truncate(MAX_TITLE_LEN));	  	
		break;			

		case 1:					  
		updateHTML("status", title.truncate(MAX_TITLE_LEN));			  	
		break;    

		case 2:
		updateHTML('status', ('Paused - ' + title).truncate(MAX_TITLE_LEN));	  	
		break;		

		case 3:
		updateHTML('status', 'Loading ...');	  	
		break;			
	} 	
}


/* -----------------------------------
* Called once the YouTube embed is loaded 
* ----------------------------------- */

function onYouTubePlayerReady(playerId) {
	normalplayer = $("playerid");
	setInterval(updateNormalPlayerInfo, 100);
	normalplayer.addEventListener("onStateChange", "onNormalPlayerStateChange");
	initSearch();	
}

function onNormalPlayerStateChange(newState) {
	normalplayer = document.getElementById("playerid");		
	setNormalPlayerState(normalplayer.getPlayerState());		
}

function updateNormalPlayerInfo() {

	var duration = getDuration();
	var currentTime = getCurrentTime();

	updateHTML("videoduration", formatTime(duration));
	updateHTML("videotime", formatTime(currentTime));
	updateProgressBar(currentTime, duration);   

	//a hack is needed due to difference in dur and time value
	duration = duration - 1;
	if((currentTime > duration) && duration > 1 && currentTime > 1){
		getNextPlaylist();
	}		
}



function isIE()
{ 
	return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}


/* -----------------------------------
* Updates the player information 
* ----------------------------------- */

function updateProgressBar(current, duration){
	
	var totalBytes = getBytesTotal();						
	var bytesLoaded = getBytesLoaded() / totalBytes;
	var startBytes = getStartBytes() / totalBytes;
	var currentTime = 1;

	if (current > 0 && duration > 0){
		currentTime = current / duration;
	}else{
		currentTime = 1;
	}

	$('progress_bar').style.width  = String(Math.round(currentTime * LOADER_WIDTH)) + "px";
	$('bytes_loaded').style.width  = String(Math.round((startBytes + bytesLoaded) * LOADER_WIDTH)) + "px";

}

function resetPlayButton() {
	$('play').hide();
	$('pause').show();
}

function seekVideo(e) {		
	if (e == null) { e = window.event }		
	mouse_x = e.clientX;
	var time = getTimeFromCur(mouse_x);				
	seekTo(time);			
}

function getTimeFromCur(mouse_x){
	var time = (mouse_x - OFFSET) / LOADER_WIDTH * getDuration();
	return parseInt(time);
}


/* -----------------------------------
* Show/Hide ajax loader
* ----------------------------------- */

function showLoader(){
	if(currentList == 'ul1'){
		$('loader').show();	
	}
}

function hideLoader(){
	$('loader').hide();	
}


/* -----------------------------------
* Format time as 00:00 
* ----------------------------------- */
function formatTime(time) {

	time = Math.round(time);

	var minutes = "";
	var seconds = "";

	if(Math.round(time % 60) < 10){
		seconds += "0";
	}

	minutes =  String(Math.floor(time / 60));	 
	seconds += String(Math.round(time % 60));

	return "0" + minutes + ":" + seconds;
}

/* -----------------------------------
* Highlights videos being played 
* ----------------------------------- */

function unselectVideos(){				
	if($(currentid + '|ul1'))
		$(currentid + '|ul1').className = "";

	if($(currentid + '|ul2'))
		$(currentid + '|ul2').className = "";		
}

function selectVideo(videoid){					
	if($(videoid + '|ul1'))
		$(videoid + '|ul1').className = "active-video";

	if($(videoid + '|ul2'))
		$(videoid + '|ul2').className = "active-video";
}

function moveNotice(e) {

	if (e == null) { e = window.event }		
	mouse_x = e.clientX;
	mouse_y = e.clientY;

	var time = (mouse_x - OFFSET) / LOADER_WIDTH * getDuration();

	$('notice').style.left = String(mouse_x + 15) + 'px';		
	$('notice').style.top = String(mouse_y + 10) + 'px';	

	if(playerState != 1){
		$('notice_body').innerHTML = "loading"
	}else{
		$('notice_body').innerHTML = formatTime(getTimeFromCur(mouse_x));						
	}
}

/* -----------------------------------
* The Key Up/Down events 
* ----------------------------------- */

function KeyCheck(e)
{
	var KeyID = (window.event) ? event.keyCode : e.keyCode; 

	switch(KeyID)
	{			  			
		case 37: //left arrow
		getPrevPlaylist();
		break;

		case 27: //up arrow
		break;

		case 39: //right arrow
		getNextPlaylist();
		break;

		case 40: //down arrow
		break;
	}
	return false;
}

/* -----------------------------------
* The play button
* Plays the first video or current video 
* ----------------------------------- */

function playButton(){				
	//play the current video
	if(currentid == 0){	
		//check for a video in the playlist first				
		var ul = $("ul2");
		var items = ul.getElementsByTagName("li");
		if(items[0]){
			playVideo(items[0].id, items[0].attributes[1].value);
		}else{		
			//otherwise pick a video in the search list
			ul = $("ul1");
			items = ul.getElementsByTagName("li");  
			if(items[0])
			playVideo(items[0].id, items[0].attributes[1].value);												
		}	
	}else{
		//play the current video
		play();
	}					
}

function showMessageBox(text){
	var messageBox = $('messageBox');
	messageBox.innerHTML = text;
	messageBox.show();
}

function hideMessageBox(){
	var messageBox = $('messageBox');
	messageBox.hide();
}


/* -----------------------------------
* disables text screen highlighting
* page feels more like a desktop app
* ----------------------------------- */

//form tags to omit:
var omitformtags=["input", "textarea", "select"]

function disableselect(e){
	for (i = 0; i < omitformtags.length; i++)
	if (omitformtags[i]==(e.target.tagName.toLowerCase()))
	return;
	return false
}

function reEnable(){
	return true
}

function noSelect(){
	if (typeof document.onselectstart!="undefined"){
		document.onselectstart=new Function ("return false")
		if (document.getElementsByTagName){
			tags=document.getElementsByTagName('*')
			for (j = 0; j < tags.length; j++){
				for (i = 0; i < omitformtags.length; i++)
				if (tags[j].tagName.toLowerCase()==omitformtags[i]){
					tags[j].onselectstart=function(){
						document.onselectstart=new Function ('return true')
					}
					tags[j].onmouseup=function(){
						document.onselectstart=new Function ('return false')
					}
				}
			}
		}
	}
	else{
		document.onmousedown=disableselect
		document.onmouseup=reEnable
	}
}

String.prototype.toCapitalCase = function() {
	var re = /\s/;
	var words = this.split(re);
	re = /(\S)(\S+)/;
	for (i = words.length - 1; i >= 0; i--) {
		re.exec(words[i]);
		words[i] = RegExp.$1.toUpperCase()
		+ RegExp.$2.toLowerCase();
	}
	return words.join(' ');
}

/* -----------------------------------
* Initializes the musicnow.fm application
* ----------------------------------- */

function init(){	
	selectSearchbox(); 		
	document.onkeyup = KeyCheck; //check for key strokes	
	YAHOO.example.DDApp.init(); // initialize the drag and drop
	noSelect();
}

window.onload = init;