<!DOCTYPE html>
<html>
<head>
  <title>4chan</title>
</head>
<body>
<script>
var SyncFrame = {
  init: function() {
    if (window.self === window.parent) {
      return;
    }
    
    this.remoteOrigin = location.protocol + '//boards.'
      + (location.host === 'boards.4channel.org' ? '4chan' : '4channel')
      + '.org';
    
    this.domain = location.host.replace(/^boards\./, '');
    
    window.addEventListener('message', this.onMessage, false);
    
    window.parent.postMessage('ready', this.remoteOrigin);
  },
  
  onMessage: function(e) {
    var self = SyncFrame;
    
    if (e.origin !== self.remoteOrigin) {
      return;
    }
    
    if (!e.data) {
      return;
    }
    
    if (e.data.storage) {
      self.setStorage(e.data.storage);
    }
    
    if (e.data.cookie) {
      self.setCookie(e.data.cookie);
    }
  },
  
  setStorage: function(data) {
    for (var key in data) {
      if (data[key] === null) {
        localStorage.removeItem(key);
      }
      else {
        localStorage.setItem(key, data[key]);
      }
    }
  },
  
  setCookie: function(data) {
    var domain, path, date, self;
    
    self = SyncFrame;
    
    date = new Date();
    
    date.setTime(date.getTime() + (data.days * 24 * 60 * 60 * 1000));
    
    if (!data.domain) {
      domain = self.domain;
    }
    else {
      domain = data.domain + self.domain;
    }
    
    if (!data.path) {
      path = '/';
    }
    else {
      path = data.path;
    }
    
    document.cookie = data.name + '=' + data.value
      + '; expires=' + date.toGMTString()
      + '; path=' + path + '; domain=' + domain;
  }
};

SyncFrame.init();
</script>
</body>
</html>
