SzaryMarian / YTWin

// ==UserScript==
// @name        YTWin
// @description View Youtube videos in separate windows
// @author      SzaryMarian
// @copyright   2016, SzaryMarian
// @license     (CC); http://creativecommons.org/licenses/by-nc-sa/3.0/
// @namespace   .
// @include     https://www.youtube.com/*
// @version     1.0
// @grant       none
// @scrurl      https://openuserjs.org/scripts/SzaryMarian/YTWin
// ==/UserScript==

window.addEventListener('load', function(){
  setTimeout(function(){
    css();
    
    //console.log(player)
    
    if(document.getElementsByClassName('yt-shelf-grid-item')){
      var I=document.getElementsByClassName('yt-shelf-grid-item');
      for(var i=0; i<I.length; i++){
        I[i].style.position='relative';
        I[i].appendChild(button(I[i].firstChild.getAttribute('data-context-item-id')));
      }
    }
    
    if(document.getElementById('watch-header')){
      var C=document.getElementById('watch-header');
      C.style.position='relative';
      C.appendChild(button(/v\=[A-Za-z0-9\-\_]+/.exec(document.URL)[0].substr(2)));
    }
  },250);
  
  function css(){
    var css="span.wn-yt-win{width:16px; height:16px; position:absolute; top:15px; right:15px; cursor:pointer; background-image:url(data:image/gif;base64,R0lGODlhEAAQAIABAP///7W1tSH5BAEKAAEALAAAAAAQABAAAAIljI+pq+Bg3kMySnhcmxl3blGa1n1hGYBbxpwr+lrXJc5Vi+dHAQA7); background-color:#888; }";
    var s=document.createElement('style');
    if(s.styleSheet)
      s.styleSheet.cssText=css;
    else
      s.appendChild(document.createTextNode(css));
    
    document.getElementsByTagName('head')[0].appendChild(s);
  }
  
  function buttonClick(id){
    var W=912;
    var H=W/(16/9);
    var win=window.open('', 'PLAYER', 'width='+W+'px,height='+H+'px,menubar=no,toolbar=no,location=no,personalbar=no');
    win.document.body.style.margin=0;

    var d=win.document.createElement('div');
    d.id='yt-player';
    win.document.body.appendChild(d);

    pageScript({
      win:win,
      width:W,
      height:H,
      id:id
    });

    YTScript(win);
  }
  function button(id){
    var s=document.createElement('span');
    s.className='wn-yt-win';
    s.addEventListener('click', function(){buttonClick(id)});
    return s;
  }
    
  function pageScript(data){
    var scr=data.win.document.createElement('script');
    var events="{onReady:function(e){e.target.playVideo();}}"
    scr.innerHTML+="var player; function onYouTubeIframeAPIReady(){player=new YT.Player('yt-player',{videoId:'"+data.id+"',width:'"+data.width+"',height:'"+data.height+"',events:"+events+"})}\n";
    data.win.document.head.appendChild(scr);
  }
  
  function YTScript(win){
      var scr=win.document.createElement('script');
      scr.src='https://www.youtube.com/iframe_api';
      win.document.head.appendChild(scr);
  }
  
  
});