var gSyncTimer = null;
var gCurrentURL = "";
var gInterval = 5000; // delay (in milliseconds)
var gUpdater = null;
var gStatus = '';
var gHistoryIDmax = 1;
var gCurrentHistoryID = null;

/**
 * Helper funciton to split a query into pieces
 */
function splitQuery(q)
{
  var argv = new Array();
  if (!q) return argv;
  var a = q.slice(1).split("&");
  for (var i=0; i<a.length; i++)
  {
    var b = a[i].split("=");
    if (!b[1]) b[1]="1"; // default value
    argv[b[0]] = window.decodeURIComponent(b[1]);
    argv.length++;
  }
  return (argv);
}


function setStatus(x) {
  if (x=='playing') {
//    $('status').innerHTML = "PLAYING";
    $('status_playing').show();
    $('status_paused').hide();
    
    gStatus = x;
  }
  else if (x=='paused') {
//    $('status').innerHTML = "PAUSED";
    $('status_paused').show();
    $('status_playing').hide();
    gStatus = x;    
  }
  else {
//    $('status').innerHTML = x;    
  }
}

function play(isStartup) {
  setStatus('playing');
  sync(null, isStartup ? 10 : 1); // the first time we fetch 10
  
  //gUpdater = new PeriodicalExecuter(sync, gInterval);
}

function pause() {
  setStatus('paused'); 
}

function goto(url) {

  // skip URL's that are known to pop out of frames
  if (url.indexOf("bloglines.com") > 0) {
    window.frames['viewer_frame'].location = "about:blank";
    return;
  }
  
  
  window.frames['viewer_frame'].location = url;
}

function sync(pe, number) {

  var username = splitQuery(parent.document.location.search)['username']; 
  if (!username) {
    var username='wanderingstan';
  }

  number = number || 1; // default to 1
  
  //setStatus('syncing ' + new Date());
  var url = 'cluztr_proxy.php';
  var params = '?method=clickstream_live&username=' + window.encodeURIComponent(username) + '&limit=' + number;
  var ajax = new Ajax.Updater
  (
    { success: syncSuccess},
    url,
    { method: 'get', parameters: params, onFailure: reportError, onSuccess: syncSuccess }
  );
}

function syncSuccess(request) {
  
  try {
    var attentionStream = eval(request.responseText);  
  }
  catch(e) {
    /*
    alert('Live Attention\n\nAn error occured:' + e.message);
    */
    gSyncTimer = setTimeout('sync()', gInterval); 
    return;
  }
  
  // if we get back lots of entries (ie we're just starting up) add them all to our history
  if (attentionStream.length > 1) {
    attentionStream.each(addToHistory);
  }
  
  var newURL = attentionStream[0].url.replace(/&amp;/g,"&");
  
  if (newURL != gCurrentURL) {
  
    if (gStatus == 'playing') {
      // go there
      goto(newURL);
      // show in history, make it current
      addToHistory(attentionStream[0], null, true);
    }
    else {
      // show in history
      addToHistory(attentionStream[0]);
    }
  }
  
  // remember where we are
  gCurrentURL = newURL;
  // show where we are
  $('current_url').innerHTML = gCurrentURL;
  
  // wait for an interval and then do it all over again
  if (gInterval<2000) gInterval=2000; // min of 2 seconds
  gSyncTimer = setTimeout('sync()', gInterval);
  

}

function reportError(request) {
  alert('Error. Stopping. Reload page to try again.');
  gUpdater.stop();
}

function addToHistory(entry, prototypeShit, makeItCurrent) {
  gHistoryIDmax ++;
  $('attention_history').innerHTML = '<div id="'+gHistoryIDmax+'"><img onclick="pause();" width="16" height="16" src="' + entry.favicon + '"/>&nbsp;<a href="#" target="_self" title="' + entry.url + '" onclick="hilite('+gHistoryIDmax+'); pause(); goto(\'' + entry.url + '\')">' + entry.title + '</a></div>' + $('attention_history').innerHTML;  
  
  // if requested, make this entry the hilited one
  if (makeItCurrent) {
    hilite(gHistoryIDmax);
  }
}

function hilite(historyID) {
  // unhilite
  if (gCurrentHistoryID) {
    $('' +gCurrentHistoryID).style.backgroundColor = "";
    $('' +gCurrentHistoryID).style.fontWeight = "";
  }
  
  $('' +historyID).style.backgroundColor = "white";
  $('' +historyID).style.fontWeight = "bold";
  
  gCurrentHistoryID = historyID;
}



