// ==UserScript==
// @name           Lunarstorm Lajv
// @namespace      http://www.lysator.liu.se/~jhs/userscript
// @description    Shows lunar lajv messages in the banner spaces
// @include        http://www.lunarstorm.se/top/top_inside*
// ==/UserScript==

if( top.seen ) return;
top.seen = {};

function visa( n, namn )
{
  var html = (n == 2 ? '' : ' |') + ' <a id=';
  return html+n+" href='javascript:top.config_gender("+n+")'>"+namn+"</a>";
};

top[0][2].location = "data:text/html;charset=iso-8859-1,<html><head><base target='lunar_main'/><style type='text/css'>a {text-decoration:none;}\na:focus{text-decoration:underline;border:none;margin:0;padding:0;}body{background:#296b84 no-repeat 50% 0;}</style></head><body><div id='msg' style='position:absolute;left:4px;right:4px;top:410px'></div><div style='position:absolute;bottom:4px;left:4px;'>Lajv:"+visa(2,"alla")+visa(1,"flickor")+visa(0,"pojkar")+visa(-1,"inga")+"</div></body>";

top.X = top[0][0].document.getElementsByTagName('iframe')[0].parentNode;
top.X.parentNode.style.background="#4D88A1"; //"#135975" //"#296B84";

//alert( 'after init' );

top.config_gender = function( n )
{
  var gender = n, msg = 'Ett ögonlock! *springer och hämtar lajvsidan*';
  if( n === undefined )
  {
    var boys = confirm( 'Visa lajv från pojkar?' ) ? 1 : 0;
    var girls = confirm( 'Visa lajv från flickor?' )? 2 : 0;
    gender = girls + boys - 1;
  }
  GM_setValue( 'gender', gender );
  var a = parseInt( ((new Date()).getTime()-2397096e5) / 315576e5 );
  var me = '{6590b5f4-e815-40df-af5f-ed163687a00e}';
  if( n < 0 )
    msg = 'Adios!';
  top.hoverLajv( me, 'Ohayou P'+a, msg );
  setTimeout( top.hoverLajv, 2e3 );
  // could be split out to an init() method:
  if( top.callBackId )
    clearInterval( top.callBackId );
  if( GM_getValue( 'gender', -1 ) >= 0 )
  {
    var x = "try{top.loadURL(top.URLLoaded);}catch(e){}";
    eval( x );
    top.callBackId = setInterval( x, 2e4 );
  }
  else
    top.X.innerHTML = '';
};

top.hoverLajv = function( id, name, msg )
{
  id = unescape( id ).toUpperCase();
  var doc = top[0][2].document;
  var div = doc && doc.getElementById( 'msg' );
  if( div )
  {
    var html = '';
    if( name )
      html += '<b><a target="lunar_main" style="color:black;" href="' +
	'http://www.lunarstorm.se/usr/usr_presentation.asp?userid='+id+'">' +
	name + '</a>' + (msg ? ':' : '') + '</b> ';
    if( msg )
      html += msg;
    div.innerHTML = html;
    if( id )
      doc.body.style.backgroundImage = 'url('+ imglink( 'large', id ) +')';
  }
};

function imglink( s, i )
{
  i = unescape( i ).toUpperCase();
  return 'http://photo.lunarstorm.se/'+s+'/'+i.substr(1,3)+'/'+i+'.jpg';
};

function loaded( q )
{
  alert(['loaded',
	 q.status,
	 q.statusText,
	 q.readyState,
	 q.responseHeaders,
	 'txt:'+(q.responseText && q.responseText.length),
	 'xml:'+q.responseXML
	 ].join("\n"));
  
};

function broken( q )
{
  alert(['broken',
	 q.status,
	 q.statusText,
	 q.readyState,
	 q.responseHeaders,
	 'txt:'+(q.responseText && q.responseText.length)
	 ].join("\n"));
  
};

msgstore = {};

function gotit( t )
{
  var xml = t.responseText, item, nr, last = 0;
  var get = /<item nr="(\d+)" message="(.*?) (.\d+):(.*?)" link=".*?id=(.*?)"/g;
  for( item in msgstore )
    last = item;
  while( item = get.exec( xml ) )
  {
    if( msgstore[ nr = item[1] ] )
      continue;
    msgstore[nr] = {nr:nr, name:item[2], age:item[3], msg:item[4], id:item[5]};
  }
  item = [];
  for( nr in msgstore )
    item.push( msgstore[nr] );
  if( nr > last )
  {
    var news = [];
    for( nr=0; nr<item.length; nr++ )
      if( item[nr].nr > last )
	news.push( item[nr] );
    //window.alert( 'news!:\n' + news.toSource() );
  }
};

top.loadURL = function( callback )
{
  var who = GM_getValue( 'gender', 2 ) + '&logmode=0';
  var url = 'http://www.lunarstorm.se/ljv/ljv_lajvlog.aspx?gender='+ who;
  GM_xmlhttpRequest( { method:'GET', url:url, headers:{ 'Accept':'text/xml' },
		       onload:function(http){ callback( http.responseText ); },
		       onerror:broken } );
  /*
  GM_xmlhttpRequest( { method:'GET', url:'http://live.lunarstorm.se/new_2.xml',
		       headers:{ 'Accept':'application/xml,text/xml' },
		       onload:gotit, onerror:broken } );
  */
};

function quoteHTML( what ){ return '&#' + what.charCodeAt(0) + ';'; };

top.URLLoaded = function( x )
{
  var i=20, T=(new Date()).getTime(), m, html = '', msg, uid, name, age, href;
  var re = /<a href="[^"]*userid=([^"]+).>([^<]+)<\/a> ([^:]+):<br>([^<]*)/ig;
  while( i-- && ( m = re.exec( x )) )
  {
    uid = unescape( m[1] );
    name = m[2];
    age = m[3];
    msg = m[4].replace( /["'&\\\n]/g, quoteHTML ).replace( /&/g, quoteHTML );
    if( (top.seen[ name ] || 0) < T )
      html += lajvFace( uid, name, age, msg );
    else
      i++;
    top.seen[ name ] = T;
  }
  if( (i < 19) && (top.X.innerHTML != html) )
    top.X.innerHTML = html;
};

function lajvFace( uid, name, age, msg )
{
  var name = name + ' ' + age;
  var html = '<div style="float:left;margin:1px 0.25ex;">';
  var code = 'top.hoverLajv("' + uid + '","' + name + '","' + msg + '")';
  var href = '/usr/usr_presentation.asp?userid=' + uid;
  html += '<a target="lunar_main" href=/usr/gst_guestbook.asp?userid=' + uid +
    '><img onmouseover=\''+ code +'\' onclick=\'setTimeout("'+ code +'",5e2)' +
    '\' onerror=this.parentNode.parentNode.style.display="none"; border="0" ' +
    'src='+ imglink( 'small', uid ) +' height="47" width="35"></a><br/>';
  html += '<div style="width:35px;text-align:center;"><a target="lunar_main"' +
    ' style=text-decoration:none; href="'+ href +'">'+ age +'</a></div></div>';
  return html;
};

setTimeout( "top[0][2].document.getElementById('2').focus();top.config_gender(2)", 50 );

