var timer;
var i =0;
var youtubediv = new Array();
function listVideos(json,divid) {
  var ul = document.createElement('ul');
  ul.setAttribute('id', 'youtubelist');
  if(json.data.items){
	  for (var i = 0; i < json.data.items.length; i++) {
	    
	var entry = json.data.items[i];
   appendOptionLast('<a href="javascript:playVideo(\''+entry.id+'\',false,\''+addslashes(entry.title)+'\',true)"><img src="'+entry.thumbnail.sqDefault+'" width="120" height="90" onmouseout="mouseOutImage(this)" onmouseover="mousOverImage(this,\''+entry.id+'\',1)"></a><br />'+entry.title.substr(0,40)+'',entry.id,'ul1');
	}
  }else{
  	divid.innerHTML = 'No Results Found';
  }
  hideLightbox();
}
var l = 1;
var youtubeInit = new Array();
function insertVideos(div,typ,q,results,start){
  start = start + 1;
var script = document.createElement('script');
  if(typ == "search"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/videos?q='+q+'&start-index='+start+'&max-results='+results+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Search: "+q.replace("+"," ")+" - YouTube Video Search";
  }
  if(typ == "user"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/users/'+q+'/uploads?max-results='+results+'&v=2&alt=jsonc&callback=youtubeInit['+l+']');
    
	if(document.title)
 		document.title = "MOVYX.COM User: "+q.replace("+"," ")+" - YouTube Video Search";
  }
if(typ == "recentlyfeatured"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/recently_featured?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Recently Featured - YouTube Video Search";
  }
if(typ == "watchonmobile"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/watch_on_mobile?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Watch On Mobile - YouTube Video Search";
  }
if(typ == "mostpopular"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM - YouTube Video Search";
  }
if(typ == "mp"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_popular?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most Popular "+q.replace("+"," ")+" Videos- YouTube Video Search";
  }
if(typ == "mostviewed"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most Viewed Videos - YouTube Video Search";
  }
if(typ == "mv"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most Viewed "+q.replace("+"," ")+" Videos - YouTube Video Search";
  }
if(typ == "mostdiscussed"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_discussed?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most Discussed Videos - YouTube Video Search";
  }
if(typ == "md"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_discussed?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most Discussed "+q.replace("+"," ")+" Videos - YouTube Video Search";
  }
	if(typ == "mostresponded"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_responded?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most responded Videos - YouTube Video Search";
  }
if(typ == "mr"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/most_responded?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Most responded "+q.replace("+"," ")+" Videos - YouTube Video Search";
  }
if(typ == "toprated"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Top Rated Videos - YouTube Video Search";
  }
if(typ == "tr"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Top Rated "+q.replace("+"," ")+" Videos - YouTube Video Search";
  }
if(typ == "topfavorites"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/top_favorites?&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Top Favorites Videos - YouTube Video Search";
  }
if(typ == "tf"){
  	script.setAttribute('src', 'http://gdata.youtube.com/feeds/api/standardfeeds/top_favorites?time='+q+'&v=2&alt=jsonc&callback=youtubeInit['+l+']&start-index=1&max-results=50&format=5');
	if(document.title)
 		document.title = "MOVYX.COM Top Favorites "+q.replace("+"," ")+" Videos - YouTube Video Search";
  }
  youtubeInit[l] = function(root) { listVideos(root,div);  };
  script.setAttribute('id', 'jsonScript');
  script.setAttribute('type', 'text/javascript');
  document.documentElement.firstChild.appendChild(script);
}
var normalplayer = false;
var currentid = 0;
var size = 1;
function getPageSize(){
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { 
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}
function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'');
	return str;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	return str;
}
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";
    }
}
(function() {
var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var DDM = YAHOO.util.DragDropMgr;
YAHOO.example.DDApp = {
    init: function() {
        var rows=1,cols=3,i,j;
        for (i=1;i<cols+1;i=i+1) {
            new YAHOO.util.DDTarget("ul"+i);
        }
        for (i=1;i<cols+1;i=i+1) {
            for (j=1;j<rows+1;j=j+1) {
                new YAHOO.example.DDList("li" + i + "_" + j);
            }
        }
    },
    showOrder: function() {
        var parseList = function(ul, title) {
            var items = ul.getElementsByTagName("li");
            var out = title + ": ";
            for (i=0;i<items.length;i=i+1) {
                out += items[i].id + " ";
            }
            return out;
        };
        var ul1=Dom.get("ul1"), ul2=Dom.get("ul2"), ul3=Dom.get("ul3");
    },
    switchStyles: function() {
        Dom.get("ul1").className = "draglist_alt";
        Dom.get("ul3").className = "draglist_alt";
    }
};
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.goingUp = false;
    this.lastY = 0;
};
YAHOO.extend(YAHOO.example.DDList, YAHOO.util.DDProxy, {

    startDrag: function(x, y) {
        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", "2px solid gray");
    },
    endDrag: function(e) {
        var srcEl = this.getEl();
        var proxy = this.getDragEl();
        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;

        a.onComplete.subscribe(function() {
                Dom.setStyle(proxyid, "visibility", "hidden");
                Dom.setStyle(thisid, "visibility", "");
            });
        a.animate();
    },
    onDragDrop: function(e, id) {
        if (DDM.interactionInfo.drop.length === 1) {
            var pt = DDM.interactionInfo.point; 
            var region = DDM.interactionInfo.sourceRegion; 
		    var srcEl = this.getEl();
			var destEl = Dom.get(id);
			if(destEl.id == "ul2"){
				var videoid = srcEl.id.replace("$", "");
				loadNewVideo(videoid);
			}
			if(destEl.id == "ul3"){
                var destDD = DDM.getDDById(id);
                destEl.appendChild(this.getEl());
                destDD.isEmpty = false;
                DDM.refreshCache();
				savePlaylist(destEl.id);
			}
        }
    },
    onDrag: function(e) {

        var y = Event.getPageY(e);

        if (y < this.lastY) {
            this.goingUp = true;
        } else if (y > this.lastY) {
            this.goingUp = false;
        }

        this.lastY = y;
    },
    onDragOver: function(e, id) {
        var srcEl = this.getEl();
        var destEl = Dom.get(id);
        if (destEl.nodeName.toLowerCase() == "li") {
            var orig_p = srcEl.parentNode;
            var p = destEl.parentNode;

            if (this.goingUp) {
                p.insertBefore(srcEl, destEl);
            } else {
                p.insertBefore(srcEl, destEl.nextSibling);
            }
            DDM.refreshCache();
        }
    }
});
Event.onDOMReady(YAHOO.example.DDApp.init, YAHOO.example.DDApp, true);
})();
	function hideLightbox(){
	}
	function onYouTubePlayerReady(playerId) {
	      normalplayer = document.getElementById("playerid");
	      setInterval(updateNormalPlayerInfo, 250);
	}
	  function cueNewVideo(id) {
	    if (normalplayer) {
	      normalplayer.cueVideoById(id);
	    }
	  }
   function updateNormalPlayerInfo() {
	  time = getCurrentTime();
	  dur = getDuration();
	  dur = dur - 1;
      if((time > dur) && dur> 1 && time > 1){
			stop();
			getNextPlaylist();
			if(document.title)
				document.title = "MOVYX.COM Next in playlist...";
	  }
    }
function getDuration() {
      if (normalplayer) {
        return normalplayer.getDuration();
      }
    }
function getCurrentTime() {
      if (normalplayer) {
        return normalplayer.getCurrentTime();
      }
    }
function play() {
      if (normalplayer) {
        normalplayer.playVideo();
      }
    }
function pause() {
      if (normalplayer) {
        normalplayer.pauseVideo();
      }
    }
function stop() {
      if (normalplayer) {
        normalplayer.stopVideo();
      }
    }
function seekTo(seconds) {
      if (normalplayer) {
        normalplayer.seekTo(seconds, true);
      }
    }
function loadNewVideo(id) {
	    if (normalplayer) {
		 	 currentid = id;
	      	normalplayer.loadVideoById(id);
	    }
	  }
function getNextPlaylist(){
			var playlistplay = 0;
			var ul = document.getElementById("ul3");
            var items = ul.getElementsByTagName("li");
            for (i=0;i<items.length;i=i+1) {
                if(items[i].id == currentid){
					var p=i+1;
					if(items[p]){
						playlistplay = 1;
						loadNewVideo(items[p].id);
						break;
					}
				}
            }
			if(playlistplay == 0 && items.length > 0)
				loadNewVideo(items[0].id);
	}
function appendOptionLast(text,id,ul){
try
	{
		if(text && id && ul){
			var list = document.getElementById(ul);
			var newNode = document.createElement("li");
			newNode.setAttribute('id',id);
			newNode.innerHTML = text;
			list.appendChild(newNode);
			if(YAHOO.example && newNode != 'null')
				new YAHOO.example.DDList(newNode);
		}
	}
	catch(err)
	{
	}
}
function clearList(ul){
	var list = document.getElementById(ul);
	while (list.firstChild) 
	 {
	    list.removeChild(list.firstChild);
	 }		
}
function mostPopular(){
	clearList('ul1');
	insertVideos('ul1','mostpopular','','50','0');
}
function mostViewed(){
	clearList('ul1');
	insertVideos('ul1','mostviewed','','50','0');
}
function mostDiscussed(){
	clearList('ul1');
	insertVideos('ul1','mostdiscussed','','50','0');
}
function mostResponded(){
	clearList('ul1');
	insertVideos('ul1','mostresponded','','50','0');
}
function recentlyFeatured(){
	clearList('ul1');
	insertVideos('ul1','recentlyfeatured','','50','0');
}
function watchonMobile(){
	clearList('ul1');
	insertVideos('ul1','watchonmobile','','50','0');
}
function topRated(){
	clearList('ul1');
	insertVideos('ul1','toprated','','50','0');
}
function topFavorites(){
	clearList('ul1');
	insertVideos('ul1','topfavorites','','50','0');
}
function makeRequest(page){
	clearList('ul1');
	var tags = encodeURI(document.getElementById('searchinput').value);
	insertVideos('ul1','search',tags,'50','0');
}
function getSearch(tags){
	clearList('ul1');
	insertVideos('ul1','search',encodeURI(tags),'50','0');
}
function getUser(tags){
	clearList('ul1');
	insertVideos('ul1','user',encodeURI(tags),'50','0');
}
function MP(tags){
	clearList('ul1');
	insertVideos('ul1','mp',encodeURI(tags),'50','0');
}
function MV(tags){
	clearList('ul1');
	insertVideos('ul1','mv',encodeURI(tags),'50','0');
}
function MD(tags){
	clearList('ul1');
	insertVideos('ul1','md',encodeURI(tags),'50','0');
}
function MR(tags){
	clearList('ul1');
	insertVideos('ul1','mr',encodeURI(tags),'50','0');
}
function TR(tags){
	clearList('ul1');
	insertVideos('ul1','tr',encodeURI(tags),'50','0');
}
function TF(tags){
	clearList('ul1');
	insertVideos('ul1','tf',encodeURI(tags),'50','0');
}
var imname;
var timer;
function mousOverImage(name,id,nr){
	if(name)
		imname = name;
	imname.src = "http://img.youtube.com/vi/"+id+"/"+nr+".jpg";
	imname.style.border = 	'3px solid #4B6AA8';
	nr++;
	if(nr > 3)
		nr = 1;
	timer =  setTimeout("mousOverImage(false,'"+id+"',"+nr+");",1000);
}
function mouseOutImage(name){
	if(name)
		imname = name;
	
	imname.style.border = 	'3px solid #fff';
	if(timer)
		clearTimeout(timer);
}
function savePlaylist(id){
	ul=YAHOO.util.Dom.get(id);
    var items = ul.getElementsByTagName("li");
	var new_playlist = "";
    for (i=0;i<items.length;i=i+1) {
         new_playlist += ""+items[i].id + "|";
    }
	var time = new Date("July 21, 2009 01:00:00")
	setCookie('playlistv2',new_playlist,time);
}
function createPlaylist(){
	var playlist = getCookie('playlistv2');
	if (playlist=="" || playlist==null){		

	}else{
		var col_array=playlist.split('|');
		var part_num=0;
		while (part_num < col_array.length)
	 	{
 			if (col_array[part_num]=='null' || col_array[part_num]==''){

			}else{

				appendOptionLast('<a href="javascript:playVideo(\''+col_array[part_num]+'\',false,\'drag and drop video\')"><img src="http://img.youtube.com/vi/'+col_array[part_num]+'/2.jpg" onmouseout="mouseOutImage(this)" onmouseover="mousOverImage(this,\''+col_array[part_num]+'\',1)"></a>',col_array[part_num],'ul3');
				
			}	
 		part_num+=1;
  		}
	}
}
function clearPlaylist(){
	deleteCookie('playlistv2');
	clearList('ul3');
}
var firsttime = true;
function playVideo(id,loader,title,clearer){
	if(document.title)
		document.title = title;
	loadNewVideo(id);
}
YAHOO.util.Event.onDOMReady(mostPopular);
YAHOO.util.Event.onDOMReady(createPlaylist);