var currentPlaylist = "";
var checkingPlaylistTimeoutHandle = null;
var timeToCheckCookiePlaylist =2000;
//**************************************************
//  Set cookie "playlist2"
//**************************************************
function setCookiePlaylist(cookieName,cookieValue,Domain) {
document.cookie = cookieName + "=" + escape(cookieValue) + 
		 ";path=/;domain=" + Domain;
}


//**************************************************
//  Get playlist (from cookie playlist2)
//**************************************************
function getPlaylist() {
	return getCookie('playlist2');
}

function isEmptyPlaylist() {
  currentCookiePlaylist = getPlaylist();   
  return (currentCookiePlaylist == null || currentCookiePlaylist == "");
}

//**************************************************
//   Get First from Playlist   return GUID
//**************************************************
function getFirstFromPlaylist(){
  var resp;
  try{
      resp=document.getElementById("playlist").childNodes[1].getAttribute('id').replace('playlist-','');
      //alert(resp);
      return resp; 
     }
  catch(err){//alert('0');
             return 0;
            }
}

//**************************************************
//     Play Next Video 
//**************************************************
function PlayNextVideo(){
var nextVideo =getFirstFromPlaylist() 
if(nextVideo!=0)
  {playFromPlaylist(nextVideo);
  }
else
  {removeFromPlaylist(document.getElementById("playlist").firstChild.getAttribute('id').replace('playlist-',''));
  }
return nextVideo;
}

//**************************************************
//     Set First Video "Now Playing" 
//**************************************************
function NowPlaying(play){

var firstGuid = document.getElementById('playlist').firstChild.getAttribute('id').replace('playlist-','');
if(play=='1')
{
 document.getElementById('NowDeleteVideo-'+firstGuid).style.display='none';
 document.getElementById('NowPlayingVideo-'+firstGuid).style.display='';
 document.getElementById('up-'+firstGuid).style.display='none';
 document.getElementById('down-'+firstGuid).style.display='none';
}
else
{document.getElementById('NowDeleteVideo-'+firstGuid).style.display='';
 document.getElementById('NowPlayingVideo-'+firstGuid).style.display='none';
 document.getElementById('up-'+firstGuid).style.display='';
 document.getElementById('down-'+firstGuid).style.display='';
}

}


//**************************************************
//   Add to Playlist and Play 
//**************************************************
//Not use anymore, now play other video is done by linking to a new page
function addToPlaylistAndPlay(guid,imageS,title){

  try { stopVideo(); } catch(e) {}
  if (guid.indexOf("{")==-1)
	guid = "{"+guid+"}";
  
  location.href = "/video/?guid="+guid;
  return;
  
  var cookiePlaylist = getCookie('playlist2');
  
  
  if ( cookiePlaylist=='null' || cookiePlaylist=='' || cookiePlaylist==null)
  {  addToPlaylist(guid,imageS,title); 
  }
  else
  {  
     if(cookiePlaylist.indexOf(guid)==-1)
     {
        removeFromPlaylist(document.getElementById("playlist").firstChild.getAttribute('id').replace('playlist-',''))      
        setEntitiesNumberInPlaylist(parseInt(document.getElementById("numEntities").innerHTML)+1)
        var NewEntity = document.createElement('li');
        NewEntity.setAttribute('id','playlist-'+guid);
        NewEntity.setAttribute('style','clear:both');
        document.getElementById("playlist").insertBefore(NewEntity,document.getElementById("playlist").firstChild);
        setNodo(guid,imageS,title);
        //addToCookiesPlaylist(guid,'1');
     }
     else
        {playFromPlaylist(guid);} 
  }
   //currentPlaylist = getCookie('playlist2');
   refreshAndPlayVideoPage(guid);
   NowPlaying('1');
}
//**************************************************
//   Prepare play of next video
//**************************************************
function prepareToPlayNextVideo(){
  try { stopVideo(); } catch(e) {}
  return true;
}

//**************************************************
//   Play From Playlist 
//**************************************************
function playFromPlaylist(guid){
  
  try { stopVideo(); } catch(e) {}
//  if (guid.indexOf("{")==-1)
//	guid = "{"+guid+"}";
  location.href = document.getElementById("url-"+guid).href;
  return;

   var hijo = document.getElementById('playlist-'+guid);
  
  if(document.getElementById("playlist").firstChild.getAttribute('id').replace('playlist-','')!=guid)
  {
       if (parseInt(document.getElementById("numEntities").innerHTML)>=2)
       { 
         removeFromPlaylist(document.getElementById("playlist").firstChild.getAttribute('id').replace('playlist-',''))
         if(parseInt(document.getElementById("numEntities").innerHTML)>2)
         {document.getElementById("playlist").insertBefore(hijo,document.getElementById("playlist").firstChild);}
         deleteFromCookiesPlaylist(hijo.getAttribute('id').replace('playlist-',''));
         //addToCookiesPlaylist(hijo.getAttribute('id').replace('playlist-',''),'1');
       }
  }
 //currentPlaylist = getCookie('playlist2');

	refreshAndPlayVideoPage(guid);
	NowPlaying('1');

////////remove this as well
/////		try {
	/////		stopPlayer();
/////		} catch(e) { alert("no pude hacer stop");}

}

//**************************************************
//   Add entity to Playlist
//**************************************************
function addToPlaylist(guid,imageS,title,url){
   
  var NewEntity = document.createElement('li');
  NewEntity.setAttribute('id','playlist-'+guid);
  
  document.getElementById("playlist").insertBefore(NewEntity,document.getElementById("playlist").firstChild.nextSibling);
  //alert(document.getElementById("playlist").firstChild.nextSibling.id);
  //document.getElementById("playlist").appendChild(NewEntity);
  setNodo(guid,imageS,title,url);
  addToCookiesPlaylist(guid,'1');
  setEntitiesNumberInPlaylist(parseInt(document.getElementById("numEntities").innerHTML)+1);
  //currentPlaylist = getCookie('playlist2');

  try
  {document.getElementById('AddRelVideo-'+guid).style.display='none';
   document.getElementById('RelVideoInMyPlay-'+guid).style.display='';
  }catch(err){}
  
  try
  {document.getElementById('AddSearch-'+guid).style.display='none';
   document.getElementById('InMyPlaySearch-'+guid).style.display=''; 
  }catch(err){}
  
  try
  {document.getElementById('AddMyFav-'+guid).style.display='none';
   document.getElementById('MyFavInMyPlay-'+guid).style.display=''; 
  }catch(err){}
  
  try
  {document.getElementById('AddBrowseVideo-'+guid).style.display='none';
   document.getElementById('BrowseVideoInMyPlay-'+guid).style.display=''; 
  }catch(err){}
  
  ProcessFavorites();

}



//**************************************************
//   setNodo to Playlist
//**************************************************
function setNodo(guid,imageS,title,url){
  var cadena='<div style="height:50px"><a id="url-'+guid+'" href="'+url+'" title="Video: '+title+'">';
  cadena=cadena+'<img width="50" height="50" src="/mm/Image//'+imageS+'" alt="Video:">';
  cadena=cadena+'<img style="margin-top:32px;margin-left:-24px;border:0" width="17" height="17" src="/images/miniplay.gif" alt="Play">';
  cadena=cadena+'</a>';
  cadena=cadena+'<a href="'+url+'" title="Video: '+title+'">';
  if(title.indexOf(':')>0) {cadena=cadena+'<strong>'+title.replace(':',':</strong><br>');}
  else {cadena=cadena+'<strong>'+title+'</strong><br><br>';}
  cadena=cadena+'</a>';  
  cadena=cadena+'<div class="favDiv" style="font-size:11px;display:none;float:left" id="fav-video-'+guid+'"></div>';
  cadena=cadena+'</div><div id="NowDeleteVideo-'+guid+'" style="float:right;font-size:11px;display:;text-align:right;margin-top:-15px">';
  cadena=cadena+'<a style="margin-right:45px" href="#" class="ajaxLink" onclick="Javascript:removeFromPlaylist('+'\''+guid+'\''+');return false;">- Remove from Playlist</a>';
  cadena=cadena+'<div style="float:right;margin-top:-16px"><a id="up-'+guid+'" href="#" onclick="moveUpInPlaylist('+'\''+guid+'\''+');return false;"><IMG alt="Move Up" style="border:0" SRC="/video/images/new/boton_up.gif" /></a>'
  cadena=cadena+'<a id="down-'+guid+'" href="#" onclick="moveDownInPlaylist('+'\''+guid+'\''+');return false;"><IMG alt="Move Down" style="border:0" SRC="/video/images/new/boton_down.gif" /></a></div>'  
  cadena=cadena+'</div><div style="display:none;font-size:11px;float:right;margin-top:-15px" id="NowPlayingVideo-'+guid+'">Now Playing</div>';
  
  document.getElementById('playlist-'+guid).innerHTML=cadena;
    
}

//**************************************************
//  Remove entity from Playlist
//**************************************************
function removeFromPlaylist(nodo){

  //---Delete <li>
    var hijo = document.getElementById('playlist-'+nodo);
    var padre = hijo.parentNode;
    var hijoRemovido = padre.removeChild(hijo);
  //---Show new number of entities
    setEntitiesNumberInPlaylist(parseInt(document.getElementById("numEntities").innerHTML)-1)
  //---Update playlist2 cookie
    //alert(getCookie('playlist2'));
    deleteFromCookiesPlaylist(nodo);
    //alert(getCookie('playlist2'));
     
  try
  {document.getElementById('AddRelVideo-'+nodo).style.display='';
   document.getElementById('RelVideoInMyPlay-'+nodo).style.display='none';
  }catch(err){}
  try
  {document.getElementById('AddSearch-'+nodo).style.display='';
   document.getElementById('InMyPlaySearch-'+nodo).style.display='none'; 
  }catch(err){}
  try
  {document.getElementById('AddMyFav-'+nodo).style.display='';
   document.getElementById('MyFavInMyPlay-'+nodo).style.display='none'; 
  }catch(err){} 
  try
  {document.getElementById('AddBrowseVideo-'+nodo).style.display='';
   document.getElementById('BrowseVideoInMyPlay-'+nodo).style.display='none'; 
  }catch(err){}
  
  //currentPlaylist = getCookie('playlist2');
    
}

//**************************************************
//  Remove all entities from Playlist
//**************************************************
function removeAllFromPlaylist(){

	cookiePlaylist = getPlaylist();
   if (cookiePlaylist!=null && cookiePlaylist!='')
   {    var firstNodoGUID=document.getElementById("playlist").firstChild.getAttribute('id').replace('playlist-','');
        var firstNodoDisplay=document.getElementById('NowDeleteVideo-'+firstNodoGUID).style.display;
        var cookiePlaylist=getCookie('playlist2');    
   
        cookiePlaylist = cookiePlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<cookiePlaylist.length-1;i++)
        {
           if ((firstNodoDisplay=='none' && firstNodoGUID!=cookiePlaylist[i]) || (firstNodoDisplay=='') )
            {
    /*            try{document.getElementById('AddRelVideo-'+cookiePlaylist[i]).style.display='';
                    document.getElementById('RelVideoInMyPlay-'+cookiePlaylist[i]).style.display='none';
                }catch(err){}
                
                try{document.getElementById('AddSearch-'+cookiePlaylist[i]).style.display='';
                    document.getElementById('InMyPlaySearch-'+cookiePlaylist[i]).style.display='none';
                }catch(err){}
                
				try{document.getElementById('AddBrowseVideo-'+cookiePlaylist[i]).style.display='';
					document.getElementById('BrowseVideoInMyPlay-'+cookiePlaylist[i]).style.display='none'; 
				}catch(err){}

                try{document.getElementById('AddMyFav-'+cookiePlaylist[i]).style.display='';
                    document.getElementById('MyFavInMyPlay-'+cookiePlaylist[i]).style.display='none';
                }catch(err){}
      */       
                removeFromPlaylist(cookiePlaylist[i]);
        //        deleteFromCookiesPlaylist(cookiePlaylist[i]);
            }
        }
                   
        if(firstNodoDisplay=='none'){
          setEntitiesNumberInPlaylist(1);
        }else{
          setEntitiesNumberInPlaylist(0);
        }
	  //currentPlaylist = getCookie('playlist2');
        
   }
    
}

//**************************************************
//  Add entity to Cookie "playlist2" 
//**************************************************
function addToCookiesPlaylist(guid,position){
 var cookiePlaylist = getCookie('playlist2');
 if(cookiePlaylist=='' || cookiePlaylist==null)
    {
	    currentPlaylist = guid+"*";
		setCookiePlaylist("playlist2",guid+"*","batanga.com");}
 else
    {if (position=='1')
      {		
	    currentPlaylist = guid+"*"+currentPlaylist;
		setCookiePlaylist("playlist2",guid+"*"+cookiePlaylist,"batanga.com");}
      else
      {
	    currentPlaylist = currentPlaylist+guid+"*";
		setCookiePlaylist("playlist2",cookiePlaylist+guid+"*","batanga.com");}
    }   
}

//**************************************************
//  Delete entity from Cookie "playlist2"
//**************************************************
function deleteFromCookiesPlaylist(guid){
    var cookiePlaylist = getCookie('playlist2');
    cookiePlaylist=cookiePlaylist.replace(guid+'*','');
	currentPlaylist = cookiePlaylist;
	setCookiePlaylist('playlist2',cookiePlaylist,'batanga.com');
}

//**************************************************
//  Show entities number in <span id="numEntities">
//**************************************************
function setEntitiesNumberInPlaylist(num){
    document.getElementById("numEntities").innerHTML=num
}


//**************************************************
//  Check entities in Related Videos removed from Playlist
//**************************************************
function checkRelatedVideosRemovedFromPlaylist(oldPlaylist)
{

   if(oldPlaylist!='') 
    {    
        oldPlaylist = oldPlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<oldPlaylist.length-1;i++)
         {  
            try{  
                document.getElementById('AddRelVideo-'+oldPlaylist[i]).style.display='';
                document.getElementById('RelVideoInMyPlay-'+oldPlaylist[i]).style.display='none';
               }catch(err){}
         }
    }
}


//**************************************************
//  Check entities in Related Videos
//**************************************************
function checkRelatedVideos()
{
 var cookiePlaylist = getCookie('playlist2');

   if( cookiePlaylist!= null && cookiePlaylist!='') 
    {    
   		//alert(cookiePlaylist+"to check related");
        cookiePlaylist = cookiePlaylist.split("*");
   		//alert("to check related"+cookiePlaylist.length);
      //--- Set Videos Relacionados  

        for (var i=0;i<cookiePlaylist.length-1;i++)
         {  
            try{  
                document.getElementById('AddRelVideo-'+cookiePlaylist[i]).style.display='none';
                document.getElementById('RelVideoInMyPlay-'+cookiePlaylist[i]).style.display='';
               }catch(err){}
         }
    }
    try{          
		var cGuidNoKeys = currentGuid.replace("{","").replace("}","");
		document.getElementById('AddRelVideo-'+cGuidNoKeys).style.display='none';
		document.getElementById('RelVideoInMyPlay-'+cGuidNoKeys).style.display='';
	}catch(err){}
}

//**************************************************
//  Check entities in Search Videos removed from Playlist
//**************************************************
function checkSearchVideosRemovedFromPlaylist(oldPlaylist)
{
 
   if(oldPlaylist!='') 
    {
        oldPlaylist = oldPlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<oldPlaylist.length-1;i++)
         {  
            try{          
                document.getElementById('AddSearch-'+oldPlaylist[i]).style.display='';
                document.getElementById('InMyPlaySearch-'+oldPlaylist[i]).style.display='none';
             }catch(err){}
         }
    }
}


//**************************************************
//  Check entities in Search Videos
//**************************************************
function checkSearchVideos()
{
 var cookiePlaylist = getCookie('playlist2');
 
   if( cookiePlaylist!= null && cookiePlaylist!='') 
    {
        cookiePlaylist = cookiePlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<cookiePlaylist.length-1;i++)
         {  
            try{          
                document.getElementById('AddSearch-'+cookiePlaylist[i]).style.display='none';
                document.getElementById('InMyPlaySearch-'+cookiePlaylist[i]).style.display='';
             }catch(err){}
         }
    }
    try{          
		var cGuidNoKeys = currentGuid.replace("{","").replace("}","");
		document.getElementById('AddSearch-'+cGuidNoKeys).style.display='none';
		document.getElementById('InMyPlaySearch-'+cGuidNoKeys).style.display='';
	}catch(err){}
    
}


//**************************************************
//  Check entities in Browse Videos removed from Playlist
//**************************************************
function checkBrowseVideosRemovedFromPlaylist(oldPlaylist)
{
   if(oldPlaylist!='') 
    {
        oldPlaylist = oldPlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<oldPlaylist.length-1;i++)
         {  
            try{          
                document.getElementById('AddBrowseVideo-'+oldPlaylist[i]).style.display='';
                document.getElementById('BrowseVideoInMyPlay-'+oldPlaylist[i]).style.display='none';
             }catch(err){}
         }
    }
    
}


//**************************************************
//  Check entities in Browse Videos
//**************************************************
function checkBrowseVideos()
{
 var cookiePlaylist = getCookie('playlist2');
 
   if( cookiePlaylist!= null && cookiePlaylist!='') 
    {
        cookiePlaylist = cookiePlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<cookiePlaylist.length-1;i++)
         {  
            try{          
                document.getElementById('AddBrowseVideo-'+cookiePlaylist[i]).style.display='none';
                document.getElementById('BrowseVideoInMyPlay-'+cookiePlaylist[i]).style.display='';
             }catch(err){}
         }
    }
    
    try{          
		var cGuidNoKeys = currentGuid.replace("{","").replace("}","");
		document.getElementById('AddBrowseVideo-'+cGuidNoKeys).style.display='none';
		document.getElementById('BrowseVideoInMyPlay-'+cGuidNoKeys).style.display='';
	}catch(err){}
}

//**************************************************
//  Check entities in MyFavorites removed from playlist
//**************************************************
function checkMyFavoritesRemovedFromPlaylist(oldPlaylist)
{
   if(oldPlaylist!='') 
    {
        oldPlaylist = oldPlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<oldPlaylist.length-1;i++)
         {
            try{          
                document.getElementById('AddMyFav-'+oldPlaylist[i]).style.display='';
                document.getElementById('MyFavInMyPlay-'+oldPlaylist[i]).style.display='none';
             }catch(err){}
         }
    }
    
}


//**************************************************
//  Check entities in MyFavorites
//**************************************************
function checkMyFavorites()
{
 var cookiePlaylist = getCookie('playlist2');
 
   if(cookiePlaylist!= null && cookiePlaylist!='') 
    {
        cookiePlaylist = cookiePlaylist.split("*");
      //--- Set Videos Relacionados  
        for (var i=0;i<cookiePlaylist.length-1;i++)
         {
            try{          
                document.getElementById('AddMyFav-'+cookiePlaylist[i]).style.display='none';
                document.getElementById('MyFavInMyPlay-'+cookiePlaylist[i]).style.display='';
             }catch(err){}
         }
    }
    
    try{          
		var cGuidNoKeys = currentGuid.replace("{","").replace("}","");
		document.getElementById('AddMyFav-'+cGuidNoKeys).style.display='none';
		document.getElementById('MyFavInMyPlay-'+cGuidNoKeys).style.display='';
	}catch(err){}
}



//**************************************************
//  Swap two guids into a string. Suppose "*" as separator
//**************************************************
function swapGuids(bigString,guid1,guid2) {
	bigString = bigString.replace(guid1+"*","#*");
	bigString = bigString.replace(guid2+"*",guid1+"*");
	bigString = bigString.replace("#*",guid2+"*");
	return bigString;
}

//**************************************************
//  Move Up in playlist
//**************************************************
function moveUpInPlaylist(guid)
{ 
	var first =getFirstFromPlaylist();
	if(first!=guid){
		if (checkingPlaylistTimeoutHandle != null)	clearTimeout(checkingPlaylistTimeoutHandle);
		var nodo=document.getElementById("playlist-"+guid);
		var previousNodo=nodo.previousSibling;
		document.getElementById("playlist").insertBefore(nodo,previousNodo);
		var cookiePlaylist = getPlaylist();
		previousGuid = previousNodo.id.replace("playlist-","");
		cookiePlaylist = swapGuids(cookiePlaylist,guid,previousGuid);
		currentPlaylist = swapGuids(currentPlaylist,guid,previousGuid);
		setCookiePlaylist("playlist2",cookiePlaylist,"batanga.com");
		checkingPlaylistTimeoutHandle = setTimeout('checkIfPlaylistWasModified();',timeToCheckCookiePlaylist);
	}
}


//**************************************************
//  Move Down in playlist
//**************************************************
function moveDownInPlaylist(guid)
{
  if(document.getElementById("playlist").lastChild.getAttribute('id').replace('playlist-','')!=guid)
   {
		var nodo=document.getElementById("playlist-"+guid);
		var nextNodo=nodo.nextSibling;
		document.getElementById("playlist").insertBefore(nextNodo,nodo);
		var cookiePlaylist = getPlaylist();
		nextGuid = nextNodo.id.replace("playlist-","");
		cookiePlaylist = swapGuids(cookiePlaylist,guid,nextGuid);
		currentPlaylist = swapGuids(currentPlaylist,guid,nextGuid);
		setCookiePlaylist("playlist2",cookiePlaylist,"batanga.com");
		checkingPlaylistTimeoutHandle = setTimeout('checkIfPlaylistWasModified();',timeToCheckCookiePlaylist);
   }
}


//**************************************************
//  Check if the playlist stored in the cookie was modified
//**************************************************
function checkIfPlaylistWasModified() {
	var cookiePlaylist = getPlaylist();
	if (cookiePlaylist==null)
		cookiePlaylist = "";	
//	firstSeparatorIndex = cookiePlaylist.indexOf("*");
//	if (firstSeparatorIndex >= 0) {
		if (cookiePlaylist != currentPlaylist) {
//			if (currentPlaylist.length > cookiePlaylist.length)
//				alert("playlist changed - mine is better, not update<BR>"+cookiePlaylist+"<BR>"+currentPlaylist);
//			else {
//				alert("playlist changed - let's update<BR>"+cookiePlaylist+"<BR>"+currentPlaylist);
				reloadPlaylist(currentGuid);
//			}
		}// else
			//alert("playlist not changed");
//	}
	
	checkingPlaylistTimeoutHandle = setTimeout('checkIfPlaylistWasModified();',4000);
}

