
 var s = "";
 var chain = "";
 var firstId = "";
 var lastId = "";
 var firstUser="";
 var secondUser = "";

 var lastReactions = [];
 var currentReaction = 0;

 var timeoutId;

 var urlRegex = new RegExp("([^:]*):[/]*(?:www\.)*([^/]+)([^\?]*)(.*)");
 var spaceRegex =new RegExp("[ \t\n\r+]+","g");
 var scale=2; 


 function photoOnOff()
 {
   var o = document.getElementById('photo');
   if (o.style.display!='none') o.style.display='none';
   else                         o.style.display='block';
 }

 function linkurl(url, keepPath, addIcon) 
 {
  urlbits = urlRegex.exec(url);
  imgtxt = "";
  if (addIcon && urlbits[1]=='http') {
    imgtxt = ['<img src="http://',urlbits[2],'/favicon.ico" class="favicon" width="16" />'].join('');
  }
  if (keepPath) {
    visualUrl = [urlbits[2],urlbits[3]].join('');
  } else {
    visualUrl = [urlbits[2]];
  }
  return [imgtxt,' <a class=\'link1\' href="',url,'" target=\'_blank\'>',visualUrl,'</a>'].join('');
 }

 function lookup()
 {
   var v = document.forms['mf'].u.value;

   if (v=='') return false;

   document.forms['mf'].submit();
 
   return true;
 }
 
function getMap(lat,lng)
{
  var s = "<a href='http://bigmap.linkstore.ru?lat="+lat
        + "&lng="+lng
        + "&zml=10"
        + "&mrk=1"         
        + "' target='_blank'>"
        + lat+","+lng
        +"</a>";

  return s;
}

function TwitterLoc(t)
{
  if (!t) return;

  var o = document.getElementById("location");
  var name = t.screen_name;
  var loc = t.location;
  var s='';

  if (loc)
  {
    re = new RegExp("([-]?[0-9]{1,3}.[0-9]+),([-]?[0-9]{1,3}.[0-9]+)","g");
    loc = loc.replace(re, getMap('$1','$2'));
    s += loc+"<br/>&nbsp;<br/>";
  }

  if (t.description)
  {
    s+="<div style='text-align:left'><strong>Bio</strong> "+t.description;
    s+="</div>";
  }

  s+="<div style='text-align:left'>";
  s+="<strong>Since:</strong> "+t.created_at+"<br/>";
  if (t.verified)
    s+="<strong>Veirifed:</strong> "+t.verified+"<br/>";
  if (t.geo_enabled)
    s+="<strong>Geo enabled:</strong> "+t.geo_enabled+"<br/>";
  if (t.protected)
    s+="<strong>Protected:</strong> "+t.protected+"<br/>";
  if (t.time_zone)
    s+="<strong>Time zone:</strong> "+t.time_zone+"<br/>";
  s+="</div>";
   
  s+= "<table border='0' cellpadding='5px' cellspacing='7px'>"
   +  "<tr><td>"
   +  "<span id='following_count' class='number'>"+t.friends_count+"</span><br/>"
   +  "<a href='http://twitter.com/"+name+"/following' id='following_count_link' class='stat' rel='"+name+"' title='See who he/she is following' target='_blank'>"
   +  "<span class='label'>following</span>"
   +  "</a>"
   +  "</td><td>"
   +  "<span id='follower_count' class='number'>"+t.followers_count+"</span><br/>"
   +  "<a href='http://twitter.com/"+name+"/followers' id='follower_count_link' class='stat' rel='"+name+"' title='See who is following him/her'>"
   +  "<span class='label'>followers</span>"
   +  "</a>"
   +  "</td>"
   +  "<td>"
   +  "<span id='update_count' class='number'>"+t.statuses_count+"</span><br/>"
   +  "<a href='http://twitter.com/"+name+"' class='stat' title='See all tweets' rel='"+name+"' target='_blank'>"
   +  "<span class='label'>tweets</span>"
   +  "</a></td>"
   +  "</tr>"
   +  "</table><br/>";

  o.innerHTML = s;
}

function cancelChain(n)
{
 lastReactions = [];
 currentReaction = 0;

 if (timeoutId)
    clearTimeout(timeoutId);

 var s="";

 if (n==1) s="Could not get dialog ";
 else      s="Could not get status ";

 s+=lastId;

 stopChain(s);   
}

function initChain()
{
 chain = "";
 lastId = "";
 firstId = "";
 firstUser="";
 secondUser = "";

 lastReactions=[];
 currentReaction = 0;
}

function stopChain(s)
{
 if (chain.indexOf("<!-- finished -->")>0) return;

 if (s.length>0)
  chain = s+ "<br/><br/>"+chain;

 if (firstUser!='' && secondUser!='')
 {
  var s ="<table border='0'><tr>";

  s+="<td valign='top'>";
  s+="<img src='"+firstUser.profile_image_url+"' alt='' border='0' width='48px' height='48px' style='float:left;padding-right:10px'/>";
  s+="<a class='link' href='http://tinfo.linkstore.ru?u="+firstUser.screen_name+"' target='_blank' title='User info'>"+firstUser.name + "</a><br/>";
  if (firstUser.description)
   s+=firstUser.description+"</br>";
  s+="</td>";

  s+="<td style='width:200px;text-align:center;font-weight:bold'>  versus </td>";

  s+="<td valign='top'>";
  s+="<img src='"+secondUser.profile_image_url+"' alt='' border='0' width='48px' height='48px' style='float:left;padding-right:10px'/>";
  s+="<a class='link' href='http://tinfo.linkstore.ru?u="+secondUser.screen_name+"' target='_blank' title='User info'>"+secondUser.name + "</a><br/>";
  if (secondUser.description)
   s+=secondUser.description+"</br>";
  s+="</td>";

  s+="</tr></table>";  

  chain = s+"<br/><br/>"+chain;

  chain +="<br/><br/>";

  s ="<table border='0'><tr>";

  s+="<td>";
  s+="From ";
  s+="<a class='link' href='http://tinfo.linkstore.ru?u="+firstUser.screen_name+"' target='_blank' title='User info'>"+firstUser.name + "</a> timeline:<br/>";
  s+="<a class='link' href='http://tlink.linkstore.ru?u="+firstUser.screen_name+"' target='_blank' title='links from timeline'>links</a> "
  s+="<a class='link' href='http://tbuzz.linkstore.ru?u="+firstUser.screen_name+"' target='_blank' title='hashtags from timeline'>buzz</a> "
  s+="<a class='link' href='http://rt.linkstore.ru?u="+firstUser.screen_name+"' target='_blank' title='retweets from timeline'>retweets</a> "
  s+="</br>";
  s+="</td>";

  s+="<td style='width:200px;text-align:center;font-weight:bold'> &nbsp; </td>";

  s+="<td>";
  s+="From ";
  s+="<a class='link' href='http://tinfo.linkstore.ru?u="+secondUser.screen_name+"' target='_blank' title='User info'>"+secondUser.name + "</a> timeline:<br/>";
  s+="<a class='link' href='http://tlink.linkstore.ru?u="+secondUser.screen_name+"' target='_blank' title='links from timeline'>links</a> "
  s+="<a class='link' href='http://tbuzz.linkstore.ru?u="+secondUser.screen_name+"' target='_blank' title='hashtags from timeline'>buzz</a> "
  s+="<a class='link' href='http://rt.linkstore.ru?u="+secondUser.screen_name+"' target='_blank' title='retweets from timeline'>retweets</a> "
  s+="</br>";
  s+="</td>";

  s+="</tr></table>";  

  chain += s+"<br/>";

  chain+="<!-- finished -->";

 }

 document.getElementById("result").innerHTML=chain;

 var share="<a class='link' href='http://twitter.com/home?status="+escape("See dialogue at http://tdialog.linkstore.ru?"+firstId)+"' title='share in Twitter'>twit this</a>"
          +" &nbsp; "  
          +"<a href='mailto:?subject=shared%20dialogue&body="+encodeURIComponent("http://tdialog.linkstore.ru?"+firstId)+"'>email</a>";

 document.getElementById("more").innerHTML=share+" &nbsp; "+"<a href='/tdialog/index.jsp' class='link' title='see a new dialog'>New dialog?</a>";
}

function setUser(tml)
{
  if (firstUser=='') firstUser = tml.user;
  else
   if (secondUser=='') secondUser = tml.user;
}

function proceedText(text)
    {
        var tweet = text;
        var re = new RegExp("(([a-zA-Z]+:\/\/)([a-zA-Z][a-zA-Z0-9_\.-]*[a-zA-Z]{2,6})([a-zA-Z0-9~\#\/\._\?\&%-=]*[a-zA-Z0-9~\#\/_\?\&%-=]))", "g");
        tweet = tweet.replace(re, '<a class="link" target="_new" href=$1 >$1</a>');
        re = new RegExp("@([a-zA-Z0-9_]+)", "g");
	tweet = tweet.replace(re, '@<a class="link" target="_new" href=http://tinfo.linkstore.ru?u=$1>$1</a>');

        re = new RegExp("#([a-zA-Z0-9_]+)", "g");
	tweet = tweet.replace(re, '<a class="link" href=http://got.linkstore.ru?q=%23$1>#$1</a>');

        tweet = tweet.replace(/&/g, '&');

        re = new RegExp("(http://twitpic.com/)([0-9a-zA-Z]*)");
	var m = re.exec(tweet);
	if  (!m || m.length == 0 || m[2] == "photos" || m[2] == "photo" || m[2] == "tag") {} 
	else {tweet = tweet+'<br/>' + '<center><a href="http://twitpic.com/' + m[2] + '" target="_blank"><img src="http://twitpic.com/show/thumb/' + m[2] + '" border=0 height=150 width=150></a></center>';}	

        re = new RegExp("(http://yfrog.com/)([0-9a-zA-Z]*)");
	m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = tweet +'<br/>' + '<center><a href="http://yfrog.com/' + m[2] + '" target="_blank"><img src="http://yfrog.com/' + m[2] + '.th.jpg" border=0 height=150 width=150></a></center>';}	

        re = new RegExp("(http://tweetphoto.com/)([0-9a-zA-Z]*)");
     	m = re.exec(tweet);
  	if  (!m || m.length == 0) {} 
 	else {tweet = tweet +'<br/>' + '<center><a href="http://tweetphoto.com/' + m[2] + '" target="_blank"><img src="http://TweetPhotoAPI.com/api/TPAPI.svc/imagefromurl?size=medium&url=http://tweetphoto.com/' + m[2] + '" border=0 height=150 width=150></a></center>';}	

        re = new RegExp("(http://plixi.com/p/)([0-9a-zA-Z]*)");
     	m = re.exec(tweet);
  	if  (!m || m.length == 0) {} 
 	else {tweet = tweet +'<br/>' + '<center><a href="http://plixi.com/p/' + m[2] + '" target="_blank"><img src="http://api.plixi.com/api/tpapi.svc/imagefromurl?size=medium&url=http://plixi.com/p/' + m[2] + '" border=0 height=150 width=150></a></center>';}	

        re = new RegExp("(http://farm)([0-9])(.static.flickr.com/)([0-9a-zA-Z_\.\/]*)");
     	m = re.exec(tweet);
  	if  (!m || m.length == 0) {} 
 	else {tweet = tweet +'<br/>' +'<center><a href="'+m[0]+'" target="_blank"><img src="'+m[0]+ '" border=0 height=150 width=150></a></center>'; }	        

        re = new RegExp("(http://twitrpix.com/)([0-9a-zA-Z]*)");
	m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = tweet +'<br/>' +'<center><a href="http://twitrpix.com/' + m[2] + '" target="_blank"><img src="http://img.twitrpix.com/thumb/' + m[2] + '" border=0 height=150 width=150></a></center>'; }	

        re = new RegExp("(http://moby.to/)([0-9a-zA-Z]*)");
	m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = tweet +'<br/>' +'<center><a href="http://moby.to/' + m[2] + '" target="_blank"><img src="http://moby.to/' + m[2] + ':medium" border=0 height=150 width=150></a></center>'; }	

        re = new RegExp("(http://twitsnaps.com/)([0-9a-zA-Z]*)");
	m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = tweet +'<br/>' +'<center><a href="http://twitsnaps.com/' + m[2] + '" target="_blank"><img src="http://twitsnaps.com/thumb/' + m[2] + '" border=0 height=150 width=150></a></center>'; }	

        re = new RegExp("(http://twitgoo.com/)([0-9a-zA-Z]*)");
	m = re.exec(tweet);
	if  (!m || m.length == 0) {} 
	else {tweet = tweet +'<br/>' +'<center><a href="http://twitgoo.com/' + m[2] + '" target="_blank"><img src="http://twitgoo.com/' + m[2] + '/thumb" border=0 height=150 width=150></a></center>'; }	
        
        return tweet;
    }


function getTweet(tml)
{
  var s="<div class='tweet'>";

  s+="<table><tr><td>";

  s+="<img src='"+tml.user.profile_image_url+"' alt='' border='0' width='48px' height='48px' style='float:left;padding-right:10px'/>";

  s+=proceedText(tml.text);

  s+="<br/>";

  s+="<span style='font-size:80%;color:#555555'>"+dateDiff(new Date(tml.created_at), new Date());

  s+=" by <a class='link' href='http://tinfo.linkstore.ru?u="+tml.user.screen_name+"' target='_blank'>"+tml.user.name+"</a>";
 
  s+="<br/>";
  s+=" <a class='link' href='http://twitter.com/home?status=@"+tml.user.screen_name+"&in_reply_to_status_id="+tml.id_str+"&in_reply_to="+tml.user.screen_name
            +"' target='_blank' title='Reply to '"+tml.user.name+"'>Reply</a> "; 
  s+="&nbsp;";
  s+=" <a class='link' href='http://twitter.com/"+tml.user.screen_name+"/statuses/"+tml.id_str
                 +"' target='_blank' title='Show tweet'>View tweet</a>";

  s+="&nbsp;";
  s+=" <a class='link' href='http://tdialog.linkstore.ru?"+tml.id_str
                 +"' target='_blank' title='Show dialog'>View dialog</a>";


  s+="</span><br/>";

  s+="<td></tr></table>";

  s+="</div>";

  return s;
}


function TwitterDialog(tml)
{
  if (timeoutId)
    clearTimeout(timeoutId);

  if (!tml)
  {
    stopChain("Could not get status "+lastId);   
    return;
  }

  if (tml.error)
  {
     stopChain(tml.error);
     return; 
  }

  setUser(tml);

  var s = getTweet(tml);

  chain = s+chain;

//alert("getdialog:"+tml.in_reply_to_status_id_str);

  if (tml.in_reply_to_status_id_str)
     getDialog(tml.in_reply_to_status_id_str);
  else
  {
//alert("ggg:"+getReaction(firstId));

     getReaction(firstUser.screen_name, firstId);
  }
}

function TwitterReaction(tml)
{
 if (timeoutId)
    clearTimeout(timeoutId);

  if (!tml)
  {
    stopChain("");
    return;
  }

  var v = tml.results;

  if (!v)
  {
    stopChain("");
    return;
  }

  if (v.length==0)
  {
    stopChain("");
    return;
  }

//alert("Reaction:"+v[0].id_str);

  currentReaction = 0;
  lastReactions = v;

  checkReaction(v[0]);  
}

function checkReaction(entry)
{
  var id = entry.id_str;
  showStatus(id);
}

function ProceedStatus(tml)
{

 if (timeoutId)
    clearTimeout(timeoutId);

  if (tml.in_reply_to_status_id_str==firstId)
  {
   var s = getTweet(tml);

   chain += s;
  }
  currentReaction++;
  if (currentReaction>=lastReactions.length) stopChain("");
  else   checkReaction(lastReactions[currentReaction]);
}

function TwitterProc(tml)
{
  if (tml.length>0)
  {
   var image = tml[0].user.profile_image_url;
   var name  = tml[0].user.screen_name;

   
   var s ="<img src='"+image+"' border='0' width='73px' height='73px' alt=''/><br/>&nbsp;<br/>";
   document.getElementById('face').innerHTML=s;

   s="";

   var replies = new Array();

   var limit = 10;

   for (var i=0; i<tml.length; i++)
   {
     var elem = tml[i];
     var txt = elem.text;

     if (i<limit) 
       s+=txt+" "; 

     if (txt.indexOf("@")==0)
     {
       var j = txt.indexOf(" ");
       if (j>2)
       {
         var r = txt.substring(1,j);
         if (r.indexOf(":")==r.length-1) 
           r = r.substring(0,r.length-1);

         addReply(replies,r);
        }  
     }

    } 

      var re = new RegExp("(([a-zA-Z]+:\/\/)([a-zA-Z][a-zA-Z0-9_\.-]*[a-zA-Z]{2,6})([a-zA-Z0-9~\#\/\._\?\&%-=]*[a-zA-Z0-9~\#\/_\?\&%-=]))", "g");
      s =  s.replace(re, ' ');
       
      re = new RegExp("[0-9]","g");
      s =  s.replace(re, ' ');

      re = new RegExp('["«»]','g');
      s =  s.replace(re, ' ');

      re = new RegExp('&lt;','g');
      s =  s.replace(re, ' ');

      re = new RegExp('&gt;','g');
      s =  s.replace(re, ' ');

      re = new RegExp('&quot;','g');
      s =  s.replace(re, ' ');

      s = SkipNoise(s);

      re = new RegExp("[-+>=~<():,@.\t'\"{}%!?\/\\\\]","g");
      s =  s.replace(re, ' ');
      
    var elems = s.split(" ");
    var cloud=[];
    var tag;
    var max = 0; 
    var res;
              
    for (var i=0; i<elems.length; i++)
    {
      tag = elems[i].toLowerCase();
      if (tag.length>3 && !isStop(tag))
      {
        res = -1;

        for (var j=0; j<cloud.length; j++)
          if (cloud[j].el==tag)
           {
               res = j;
               j = cloud.length+1;               
           }


           if (res<0)
           {
             cloud[cloud.length] = { count: 1, el: tag };
             max = Math.max(1, max);
           }
           else 
           {
             cloud[res].count += 1;
             max = Math.max(cloud[res].count, max);
           }

       }
          
   }
      
    s='';    
    for (var i = 0; i < cloud.length; i++) {
      if (cloud[i].count>=2)
       //s+='<a class="link1" style="font-size:' + Math.ceil((cloud[i].count / max) * scale) + 'em" href="http://search.twitter.com/search?q='+cloud[i].el+'" target="_blank">' + cloud[i].el + '</a> &nbsp; ';
       s+='<a class="link1" style="font-size:' + Math.ceil((cloud[i].count / max) * scale) + 'em" href="http://got.linkstore.ru?q='+encodeURIComponent(cloud[i].el)+'" target="_blank">' + cloud[i].el + '</a> &nbsp; ';
      else
       s+='<span style="color:blue;font-size:' + Math.ceil((cloud[i].count / max) * scale) + 'em">' + cloud[i].el + '</span> &nbsp; ';
    }

    var ans = "<span style='font-size:150%'>Recent topics:</span><br/><br/> "+ s;

    if (replies.length>0)
    {
      ans += "<br/><br/><span style='font-size:150%'>Recently replied to:</span><br/><br/>";
      for (var i=0; i<replies.length; i++)
       ans+="<a class='link1' href='http://tinfo.linkstore.ru?u="+replies[i]+"'>"+replies[i]+"</a> &nbsp; ";
    }

    ans += "<br/><br/><span style='font-size:150%'>Reads:</span><br/><br/>";

    ans+="<a class='link1' href='http://tlink.linkstore.ru?u="+name+"'>links from friends</a> &nbsp; ";
    ans+="<a class='link1' href='http://rt.linkstore.ru?u="+name+"'>retweets from friends</a> &nbsp; ";
    ans+="<a class='link1' href='http://tbuzz.linkstore.ru?u="+name+"'>buzz from friends</a> &nbsp; ";

    document.getElementById('cloud').innerHTML = ans;
  }
}

function addReply(ara, r)
{
  for (var i=0; i<ara.length; i++)
   if (ara[i]==r) return;

  ara[ara.length]=r;
}

function getDialog(user)
{
  lastId=user;
  if (firstId=='') firstId = user;
  timeoutId = setTimeout("cancelChain(1)",15000);

  var cbscript = document.createElement("script");
  cbscript.src = 'http://twitter.com/statuses/show/'+user+'.json?callback=TwitterDialog';
  cbscript.type = 'text/javascript';
  document.body.appendChild(cbscript);
}

function showStatus(id)
{
  timeoutId = setTimeout("cancelChain(2)",15000);

  var cbscript = document.createElement("script");
  cbscript.src = 'http://twitter.com/statuses/show/'+id+'.json?callback=ProceedStatus';

//alert("get status:"+cbscript.src);

  cbscript.type = 'text/javascript';
  document.body.appendChild(cbscript);
}

function getTwitterFace(user)
{
  var cbscript = document.createElement("script");
  cbscript.src = 'http://twitter.com/statuses/user_timeline/'+user+'.json?callback=TwitterProc&count=20';
  cbscript.type = 'text/javascript';
  document.body.appendChild(cbscript);
}

function getReaction(user, since)
{
  var cbscript = document.createElement("script");

  if (since)
    cbscript.src = 'http://search.twitter.com/search.json?q=to%3A'+user+'&since_id='+since+'&callback=TwitterReaction';
  else
    cbscript.src = 'http://search.twitter.com/search.json?q=to%3A'+user+'&callback=TwitterReaction';

//alert("get reactions:"+cbscript.src);

  cbscript.type = 'text/javascript';
  document.body.appendChild(cbscript);
}

function getLocation(user)
{
  var cbscript = document.createElement("script");
  cbscript.src = 'http://twitter.com/users/show/'+user+'.json?callback=TwitterLoc';
  cbscript.type = 'text/javascript';
  document.body.appendChild(cbscript);
}

function dateDiff(d1, d2)
   {
     var diff  = new Date();

     diff.setTime(Math.abs(d1.getTime() - d2.getTime()));

     var timediff = diff.getTime();

     var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
     timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

     var days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
     timediff -= days * (1000 * 60 * 60 * 24);

     var hours = Math.floor(timediff / (1000 * 60 * 60)); 
     timediff -= hours * (1000 * 60 * 60);

     var mins = Math.floor(timediff / (1000 * 60)); 
     timediff -= mins * (1000 * 60);

     var secs = Math.floor(timediff / 1000); 
     timediff -= secs * 1000;

     var ans ="";
     if (weeks!=0) ans+=weeks+" weeks ";

     if (days!=0)  ans+=days+" days ";

     if (hours!=0) ans+=hours+" hours ";
     else
     {
       if (mins!=0)  ans+=mins+" mins ";   
       else
          ans += secs +" secs "    
     }

     return ans+"ago";
   }




