<!DOCTYPE html>
<html>
  <head>
    <title>Example webrtc.io</title>
    <link type="text/css" href="/style.css" rel="stylesheet"></link>

    <script src="http://multiwebrtc.nodejitsu.com/socket.io/socket.io.js"></script>
    <script src="/io.js"></script>

    <script type="text/javascript">

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-31155783-4']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();

    </script>

  </head>
  <body onload="init()">
    <div id="videos">
      <a href="https://github.com/dennismartensson/webrtc.io-demo"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png" alt="Fork me on GitHub"></a>
      <video id="you" autoplay></video>
    </div>
    <div id="chatbox">
      <button id="fullscreen">Enter Full Screen</button>
      <div id="messages">
      </div>
      <br>
      <input id="chatinput" type="text"/>
    </div>
    <script>
      var videos = [];

      function getNumPerRow() {
        var len = videos.length;
        var biggest;

        // Ensure length is even for better division.
        if (len % 2 === 1) {
          len++;
        }

        biggest = Math.ceil(Math.sqrt(len));
        while (len % biggest !== 0) {
          biggest++;
        }
        return biggest;
      }

      function subdivideVideos() {
        var perRow = getNumPerRow();
        var numInRow = 0;
        for (var i = 0, len = videos.length; i < len; i++) {
          var video = videos[i];
          setWH(video, i);
          numInRow = (numInRow + 1) % perRow;
        }
      }

      function setWH(video, i) {
        var perRow = getNumPerRow();
        var perColumn = Math.ceil(videos.length / perRow);
        var width = Math.floor((window.innerWidth) / perRow);
        var height = Math.floor((window.innerHeight - 190) / perColumn);
        console.log(width, height);
        video.width = width;
        video.height = height;
        video.style.position = "absolute";
        video.style.left = (i % perRow) * width + "px";
        video.style.top = Math.floor(i / perRow) * height + "px";
      }

      function cloneVideo(domId, socketId) {
        var video = document.getElementById(domId);
        var clone = video.cloneNode(false);
        clone.id = "remote" + socketId;
        document.getElementById('videos').appendChild(clone);
        videos.push(clone);
        return clone;
      }
      function removeVideo(socketId) {
        var video = document.getElementById('remote' + socketId);
        if (video) {
            videos.splice(videos.indexOf(video), 1);
            video.parentNode.removeChild(video);
        }
      }

      function initChat() {

        var input = document.getElementById("chatinput");
        input.addEventListener('keydown', function(event) {
          var key = event.which || event.keyCode;
          if (key === 13) {
            rtc._socket.emit('chat msg', input.value);
            addToChat(input.value);
            input.value = "";
          }
        }, false);
        rtc._socket.on('receive chat msg', function(data) {
          console.log(data.color);
          addToChat(data.msg, data.color.toString(16));
        });
      }

      function addToChat(msg, color) {
        var messages = document.getElementById('messages');
        msg = sanitize(msg);
        if (color) {
          msg = '<span style="color: #' + color + '; padding-left: 15px">' + msg + '</span>';
        } else {
          msg = '<strong style="padding-left: 15px">' + msg + '</strong>';
        }
        messages.innerHTML = messages.innerHTML + msg + '<br>';
        messages.scrollTop = 10000;
      }

      function sanitize(msg) {
        return msg.replace(/</g, '&lt;');
      }

      function initFullScreen(){ 
        var button = document.getElementById("fullscreen");
        button.addEventListener('click', function(event) {
          var elem = document.getElementById("videos"); 
          //show full screen 
          elem.webkitRequestFullScreen();
        });
      } 

      function init() {
        rtc.createStream('you', function(stream) {
          videos.push(document.getElementById('you'));
          rtc.attachStream(stream, 'you');
          subdivideVideos();
        });

        rtc.connect("http://multiwebrtc.nodejitsu.com/");
        rtc.on('add remote stream', function(stream, socketId) {
          console.log("ADDING REMOTE STREAM...");
          var clone = cloneVideo('you', socketId);
          rtc.attachStream(stream, clone.id);
          subdivideVideos();
        });
        rtc.on('disconnect stream', function(data) {
            console.log('remove ' + data);
            removeVideo(data);
        });
        initChat();
        initFullScreen();
      }
      
      function onClose(data) {
//        video.parentNode.removeChild(video);
      }

      window.onresize = function(event) {
        subdivideVideos();
      };
    </script>
  </body>
</html>