var curVideoId = "";
var curVideoTitle = "";
var myIdList = new Array();
var myTitleList = new Array();
var myTimer = 0;
var ytplayer = null;
var playerShown = false;
var playerWidth = 500;
var playerHeight = 375;	

function updateHTML(id, value) {
	document.getElementById(id).innerHTML = value;
}
	
function updateTitle(title) {
	document.getElementById("videoTitle").innerHTML = unescape(title);
}

function updateGFC(id,title) {
    vidid = "PTV-" + id;
    var skin = {};
    skin['BORDER_COLOR'] = '#cccccc';
    skin['ENDCAP_BG_COLOR'] = '#e0ecff';
    skin['ENDCAP_TEXT_COLOR'] = '#333333';
    skin['ENDCAP_LINK_COLOR'] = '#0000cc';
    skin['ALTERNATE_BG_COLOR'] = '#ffffff';
    skin['CONTENT_BG_COLOR'] = '#ffffff';
    skin['CONTENT_LINK_COLOR'] = '#0000cc';
    skin['CONTENT_TEXT_COLOR'] = '#333333';
    skin['CONTENT_SECONDARY_LINK_COLOR'] = '#7777cc';
    skin['CONTENT_SECONDARY_TEXT_COLOR'] = '#666666';
    skin['CONTENT_HEADLINE_COLOR'] = '#333333';
    skin['DEFAULT_COMMENT_TEXT'] = 'Write your comment here';
    skin['HEADER_TEXT'] = 'Ratings';
    skin['POSTS_PER_PAGE'] = '10';
    google.friendconnect.container.setParentUrl('/' /* location of rpc_relay.html and canvas.html */);
    google.friendconnect.container.renderReviewGadget(
    { id: 'div-5152550616525517098',
    site: '06526340989662850781',
    'view-params':{"disableMinMax":"false","scope":"ID","docId":vidid,"startMaximized":"true"}
    },
    skin);

    purl = "http://www.philippinestoday.net/video/index.php?mod=video&id=" + id;
    var skin1 = {};
    skin1['HEIGHT'] = '73';
    skin1['BORDER_COLOR'] = '#cccccc';
    skin1['ENDCAP_BG_COLOR'] = '#e0ecff';
    skin1['ENDCAP_TEXT_COLOR'] = '#333333';
    skin1['BUTTON_STYLE'] = 'modular';
    skin1['BUTTON_TEXT'] = 'Recommend it!';
    skin1['BUTTON_ICON'] = 'default';
    skin1['BUTTON_MODULE_PROMO_TEXT'] = 'Did you like this video?';
    google.friendconnect.container.renderOpenSocialGadget(
    { id: 'div-9212695474565119995',
        url:'http://www.google.com/friendconnect/gadgets/recommended_pages.xml',
        height: 73,
        site: '06526340989662850781',
        'view-params':{"pageUrl":purl,"pageTitle":title,"docId":"recommendedPages"}
    },
    skin1);
}

function addItemToPlayList(id,title) {
	myIdList.push(id);
	myTitleList.push(title);
	addOptionElement(title);
}
	
function onPlayerStateChange(newState) {
	if (newState === 0) {
		if (ytplayer) {
			if ((ytplayer.getDuration() > 0) && ((ytplayer.getCurrentTime()-ytplayer.getDuration()) < 1.0)) {
				if (myIdList.length > 0) {
					id = myIdList[0];
					title = myTitleList[0];
					myIdList.splice(0,1);
					myTitleList.splice(0,1);
					loadNewVideo(id,title);
					removeOptionElement(0);
				}
			}
		}
	}
}
	
function updatePlayerStatus() {
	str = "<b>play time:</b> "
	if (ytplayer) {
		gct = (ytplayer.getCurrentTime() < 0)?0:ytplayer.getCurrentTime();
		dur = (ytplayer.getDuration() < 0)?0:ytplayer.getDuration();
		str += gct + "  s of " + dur + " s<br />";
		loaded = (ytplayer.getVideoBytesLoaded() < 0)?0:ytplayer.getVideoBytesLoaded();
		bytotal = (ytplayer.getVideoBytesTotal() < 0)?0:ytplayer.getVideoBytesTotal();			
		str += "<b>loaded:</b> " + loaded + " bytes of " + bytotal + " bytes<br />";
		str += "<b>status:</b> " + getPlayerState(ytplayer.getPlayerState());
		updateHTML("playerstatus",str);
	}
}
	
function addOptionElement(title) {
	var opt = document.createElement("option");
	var sel = document.getElementById("playListSelect");
	opt.text = (title.length > 30)?(title.substr(0,30) + " ..."):title;
	try {
		sel.add(opt,null); // standards compliant
	} catch(ex) {
		sel.add(opt); // IE only
	}
}
	
function removeOptionElement(num) {
	var sel = document.getElementById("playListSelect");
	sel.remove(num);
}

function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById("myytplayer");
	if (ytplayer) {
		if (curVideoId.length > 0) cueNewVideo(curVideoId,curVideoTitle);
		ytplayer.setVolume(100);
		ytplayer.addEventListener("onStateChange","onPlayerStateChange");
		if (myTimer == 0) myTimer = setInterval("updatePlayerStatus()",500);
		playerShown = true;
	}
}

function loadYoutubePlayer() {
	if (document.getElementById("videoPlayer") != null) {
	    var ptDevId = 'AI39si7Yr11-GsUlcexvJHIiNCUhRTqk1z4AhrLn7swHiEMuJei2FyGGmmWo88PW_tfcWuSIQCohkTnr7ysPUEgbK13chu0haQ';
   		// allowScriptAccess must be set to allow the Javascript from one 
    	// domain to access the swf on the youtube domain	  
    	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's API
	    var atts = { id: "myytplayer" };
		/*
   		swfobject.embedSWF("http://gdata.youtube.com/apiplayer?key=" + ptDevId + "&enablejsapi=1&playerapiid=ytplayer", 
       						"videoPlayer", playerWidth, playerHeight, "8", null, null, params, atts);
							*/
   		swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer", 
       						"videoPlayer", playerWidth, playerHeight, "8", null, null, params, atts);
								
	} else {
		setTimeout("loadYoutubePlayer()",1000);
	}
}

function getYoutubeUnit(qry,url,id) {
	if (!playerShown) {
		playerWidth = 400;
		playerHeight = 330;
		str = url + '?vq=' + urlEncode(qry) + '&orderby=published&start-index=1&max-results=5&format=5&tag-get=youtubeunit&tag-id='+id;
		getList(id,str);
		setTimeout("loadYoutubePlayer()",1000);
	}
}

function closeYoutubeUnit(id) {
	if (ytplayer) {
		ytplayer.stopVideo();
	}
	if (myTimer > 0) {
		clearInterval(myTimer);
		myTimer = 0;
	}
	updateHTML(id,"");
	playerShown = false;
}

function loadNewVideo(id, title) {
	if (ytplayer) {
		ytplayer.loadVideoById(id, 0);
		updateTitle(title);
        updateGFC(id,title);
		curVideoId = id;
		curVideoTitle = title;
	}
}

function cueNewVideo(id, title) {
	if (ytplayer) {
		ytplayer.cueVideoById(id, 0);
		updateTitle(title);
	}
}

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

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

function stopPlayer() {
	if (ytplayer) {
		ytplayer.stopVideo();
		cueNewVideo(curVideoId,curVideoTitle);
	}
}
	
function getPlayerState(id) {
	str = "";
	if (ytplayer) {
		if (id == -1) str = "Unstarted";
		else if (id == 0) str = "Stopped";
		else if (id == 1) str = "Playing";
		else if (id == 2) str = "Paused";
		else if (id == 3) str = "Buffering";
		else if (id == 5) str = "Cued";
	}
	return str;
}
	
function skipPlay() {
	if (ytplayer) {
		if (myIdList.length > 0) {
			id = myIdList[0];
			title = myTitleList[0];
			myIdList.splice(0,1);
			myTitleList.splice(0,1);
			loadNewVideo(id,title);
			removeOptionElement(0);
		}		
	}
}
	
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try {
  		// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	} catch (e)
  	{
  		// Internet Explorer
  		try {
    		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	} catch (e)
    	{
    		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    	}
  	}
	return xmlHttp;
}

function search_yt(url,outid) {
	vq = urlEncode(document.getElementById('searchbox').value);
	orderby = document.getElementById('selectmenu').value;
	if (orderby == "userfeed") {
		str = url + '?vq=' + vq + '&orderby=published&start-index=1&max-results=5&format=5&tag-get=userfeed&tag-id='+outid;
	} else {
		str = url + '?vq=' + vq + '&orderby=' + orderby + '&start-index=1&max-results=5&format=5&tag-get=search&tag-id='+outid;
	}
	getList(outid,str);
}
	
function getUserList(user,url) {
	str = url + '?vq=' + user + '&orderby=published&start-index=1&max-results=5&format=5&tag-get=userfeed&tag-id=searchresult';
	getList('searchresult',str);		
}

function getSearchTerm(str,url,tid) {
	str = url + '?vq=' + urlEncode(str) + '&orderby=published&start-index=1&max-results=5&format=5&tag-get=search&tag-id='+tid;
	getList('searchresult',str);		
}

function getList(id,qry) {
	var xmlHttp;
	
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp != null) {
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				document.getElementById(id).innerHTML = xmlHttp.responseText;
			}
		}
		xmlHttp.open("GET",qry,true);
		xmlHttp.send(null);
	}
}

function urlEncode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

function urlDecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}