/* ------------------------------------------------------
Name:		playerlist.js
Description:	functions for player and listing of videos
Author:		Videoevolved.com damon lynn adapted by Grita Fuerte
Author URI:	http://www.videoevolved.com, http://www.gritafuerte.com
Date:			2007-11-26

Last Edit		Who	Description
-----------		---	---------------
2007-12-14            JP      Added condition at totalvids variable
2007-12-18            JP      Put number of views on current video.
2007-12-19		JP	Add new function tab(m) for tabs ajax
2007-12-20	JP	Removed tab function
2008-02-06	EA	added number_format function
2008-03-08	EA	modified getflv to include path to trapvid.php file
2009-01-26	EA	added functions for youtube chromeless flash player
------------------------------------------------------
*/


//==================================================================================
//	youtube chromeless player functions
//==================================================================================

var vid;
vid=0;  // need toget this from post - probably "1", but may be another number

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

        function setytplayerState(newState) {
          //updateHTML("playerstate", newState);
        }

        function onYouTubePlayerReady(playerId) {
          ytplayer = document.getElementById("myytplayer");
          setInterval(updateytplayerInfo, 250);
          updateytplayerInfo();
          ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
		  loadNewVideo(videos[0]['id'],0);	//always show the intro video
        }

		// States: unstarted:  -1, ended: 0,  playing: 1,  paused: 2,  buffering:  3, cued:  5
        function onytplayerStateChange(newState) {
          setytplayerState(newState);
		  if(newState==-1) {play();}
		  if(newState==0) {jump_to(vid+1,1);}
        }

        function updateytplayerInfo() {
        /*
		updateHTML("bytesloaded", getBytesLoaded());
	          updateHTML("bytestotal", getBytesTotal());
	          updateHTML("videoduration", getDuration());
	          updateHTML("videotime", getCurrentTime());
	          updateHTML("startbytes", getStartBytes());
	          updateHTML("volume", getVolume());
		  */
		  //number_format(videos[x]['view_count'],0,'.',',')
		  //updateHTML( "videotime", number_format(getCurrentTime(),0,'.',',')+'/'+number_format(getDuration(),0,'.',',') );
		  //updateHTML( "videotime", hhmmss(getCurrentTime())+' ('+Math.round(100*getCurrentTime()/getDuration())+'%) <br /> '+hhmmss(getDuration()) );
			if(getCurrentTime()>0){
				updateHTML( "videotime", hhmmss(getDuration())+' ('+Math.round(100*getCurrentTime()/getDuration())+'%)' );
			}
		}

        // functions for the api calls
        function loadNewVideo(id, startSeconds) {
          if (ytplayer) {
            ytplayer.loadVideoById(id, parseInt(startSeconds));
          }
        }

        function cueNewVideo(id, startSeconds) {
          if (ytplayer) {
            ytplayer.cueVideoById(id, startSeconds);
          }
        }

        function play() {
          if (ytplayer) {
            ytplayer.playVideo();
          }
        }

        function pause() {
          if (ytplayer) {
            ytplayer.pauseVideo();
          }
        }

        function stop() {
          if (ytplayer) {
            ytplayer.stopVideo();
          }
        }

        function getPlayerState() {
          if (ytplayer) {
            return ytplayer.getPlayerState();
          }
        }

        function seekTo(seconds) {
          if (ytplayer) {
            ytplayer.seekTo(seconds, true);
          }
        }

        function getBytesLoaded() {
          if (ytplayer) {
            return ytplayer.getVideoBytesLoaded();
          }
        }

        function getBytesTotal() {
          if (ytplayer) {
            return ytplayer.getVideoBytesTotal();
          }
        }

        function getCurrentTime() {
          if (ytplayer) {
            return ytplayer.getCurrentTime();
          }
        }

        function getDuration() {
          if (ytplayer) {
            return ytplayer.getDuration();
          }
        }

        function getStartBytes() {
          if (ytplayer) {
            return ytplayer.getVideoStartBytes();
          }
        }

        function mute() {
          if (ytplayer) {
            ytplayer.mute();
          }
        }

        function unMute() {
          if (ytplayer) {
            ytplayer.unMute();
          }
        }
        
        function getEmbedCode() {
          alert(ytplayer.getVideoEmbedCode());
        }

        function getVideoUrl() {
          alert(ytplayer.getVideoUrl());
        }
        
        function setVolume(newVolume) {
          if (ytplayer) {
            ytplayer.setVolume(newVolume);
          }
        }

        function getVolume() {
          if (ytplayer) {
            return ytplayer.getVolume();
          }
        }

        function clearVideo() {
          if (ytplayer) {
            ytplayer.clearVideo();
          }
        }
		
//==================================================================================

function jump_to(x,y){
     
	 if(typeof(totalvids) != 'undefined') {
		 if(totalvids>0){

		 //document.getElementById('myctrl').style.display='block';
			//document.getElementById('listingcomments').style.display='none';
		 	//sendEvent('stop');
			/*
				if(typeof(mycvid)!='undefined'){
					document.getElementById('div'+mycvid).style.backgroundColor="#000000";	
					document.getElementById('div'+mycvid).style.color="#FFFFFF";
				}else{
					document.getElementById('div'+x).style.backgroundColor="#000000";
					document.getElementById('div'+x).style.color="#FFFFFF";
				}
			*/
				//document.getElementById('div'+x).style.backgroundColor="#000000";
				//document.getElementById('div'+x).style.color="#FFFFFF";
				
				if(x>=totalvids){x=0;}
				if(x<0){x=totalvids-1;}
				if(y==1){vid=x;}else{mycvid=playorder[x];}
				vid=x;
				//getflv(videos[mycvid]['id']);
				loadNewVideo(videos[x]['id'],0);
				//updateHTML( "tmp", vid+', '+videos[x]['id'] );

				update_playing(x);
				document.getElementById('div'+x).style.backgroundColor="#FFCCFF";
				document.getElementById('div'+x).style.color="#FFFFFF";

				play();
				document.getElementById('page').value = 1;
				prepare_entries();
		}
    }
}

function shuffle_list(z){
		if(z.checked==true){
		playorder.sort(function() {return 0.5 - Math.random()}) //Array elements now scrambled
	}else{
		unshuffle();
	}

	
}

function unshuffle(){
	playorder=new Array; 
	for(i=0;i<totalvids;i++){
		playorder[i]=i;
	}
}

function update_playing(x){
	document.getElementById('playing').innerHTML = "<div><h5>"+videos[x]['title'].substring(0,75)+"</h5></div><img src='"+videos[x]['thumbnail_url']+"' style='float:right;padding:4px;border:1px solid;'>";
	//document.getElementById('playing').innerHTML+= "<p>Views : "+videos[x]['view_count']+" </p><p>Ratings: "+videos[x]['rating_count']+" | Average Rating: "+videos[x]['rating_avg']+"</p>";
	document.getElementById('playing').innerHTML+= "Reproducciones: "+number_format(videos[x]['view_count'],0,'.',',')+"<br /><br />";
	document.getElementById('playing').innerHTML+="<div id='playing_desc'>"+videos[x]['description'].substring(0,250)+"</div>";
	document.getElementById('playing').innerHTML+= "";
	
//show comments that go with the video
	document.getElementById('playing').innerHTML+= "<input type='hidden' id='postid' name='postid' value='"+videos[mycvid]['postid']+"'>";

	var postid = document.getElementById('postid');
	var page = document.getElementById('page');
	strQuery = 'type=1&page='+page.value+'&postid='+postid.value;
	//strQuery = 'p='+postid.value;
	var functionName = function(oXML) { process_entries(oXML); };
	sendPacket(phpFileName, strQuery, functionName);

	document.getElementById('videohide').innerHTML = "<input type='hidden' id='postid' name='postid' value='"+videos[mycvid]['postid']+"'>";
}

function openhelp(x){
	window.open(x,'helpwindow','menubar=1,resizable=1,width=350,height=250');
}

function number_format(a, b, c, d) {
	// number_format(number, decimals, comma, formatSeparator)
	a = Math.round(a * Math.pow(10, b)) / Math.pow(10, b);
	e = a + '';
	f = e.split('.');
	if(!f[0]) f[0] = '0';
	if(!f[1]) f[1] = '';
	if(f[1].length < b){
		g = f[1];
		for(i = f[1].length + 1; i <= b; i++) {
			g += '0';
		}
		f[1] = g;
	}
	if(d != '' && f[0].length > 3) {
		h = f[0];
		f[0] = '';
		for(j = 3; j < h.length; j += 3) {
			i = h.slice(h.length - j, h.length - j + 3);
			f[0] = d + i +  f[0] + '';
		}
		j = h.substr(0, (h.length % 3 == 0) ? 3 : (h.length % 3));
		f[0] = j + f[0];
	}
	c = (b <= 0) ? '': c;
	return f[0] + c + f[1];
}

function hhmmss(x){
	// convert time to hh:mm:ss
	hours=Math.floor(x/3600);
	minutes=Math.floor((x%3600)/60);
	seconds=Math.round((x%3600)%60);
	mseconds=Math.round(((((x%3600)%60)*100)/100)-seconds);

	if(!hours==0) {
		hours=hours+"h";
	}
	
	if(!minutes==0) {
		minutes=minutes+"m";
	}
	
	return hours+minutes+seconds+'s';
}

function pad(num){
   num=num+"";
   if(num.length==1){
	   num="0" + num;
   }
  
   return num;   
}
   