// TwitterFish Javascript Library
// Copyright 2009 by Andrew Gent. All Rights Reserved.
// Some functions of this application are provided by and copyrighted 
// by Google and Twitter.


var tweets = [];
var tweetcount;
var bucket = '';
var tfURL = "twitterfish.html";

function tfDebugger(t) { 
      //alert(t); return;
	//bucket += "<br/>" + t;
      //document.getElementById("debugging").innerHTML = bucket; 
}

function tfLoader() {

	// Load the appropriate language UI elements
  tfglBuildLanguageSelector();

	// Put in the appropriate branding elements
  var x = document.getElementById('googlebrand');
  if (x) { x.innerHTML = ""; }
  google.language.getBranding('googlebrand');

	// Check the user's defaults.
  tfCheckSettings();

	// Set the login UI box
  // TBD

	// Look up the current status
  tfTwitterStatus();
}


//================================================
//		User Interface Functions
//================================================

var tfcfgLanguage;
var tfcfgViewID;
var tfcfgViewType;
var tfcfgUsername;
var tfcfgPassword;


function tfglBuildLanguageSelector() {
  var t = '';
  var mbox = document.getElementById("languagemenudiv");
  for (lang in google.language.Languages) {
     t += '<option value="' + google.language.Languages[lang] + '">' + tfInitCap(lang) + "</option>\n";
  }
  if (mbox) mbox.innerHTML = '<select id="languagemenu" rows="1" onchange="javascript:ChangeLanguage();">' + t + '</select>';

}

function tfCheckSettings() {
   var tfUserLang = "en";
   var tfUserViewID = "_public";
   var tfUserViewType = "1";
   var tfUserName = "";
   var tfUserPassword = "";
   var t; var i;

	// Look up the cookies
   tfcfgLanguage = tfGetCookie("language");
   if (tfcfgLanguage == "") tfcfgLanguage = tfUserLang;		//set the default.

	// Check to see if this is public view of a private view.
   t = tfGetCookie("userID");
   if (t != "") {
   	t = unescape(t);
	i = t.indexOf(":");
	tfcfgUsername = t.substring(0,i);
	tfcfgPassword = t.substring(i+1);
	tfcfgViewType = "2";
   } else {
	tfcfgUsername = "";
	tfcfgPassword = "";
   	tfcfgViewType = "1";
   }
   
	// The settings don't matter if a user ID is passed in as an argument.
   tfcfgViewID = ""
   t = window.location.href;
   i = t.indexOf("?");
   if (i>0) {
	t = t.substring(i+1);
 	//alert("Parameters are: " + t);
      if (t.indexOf("id=") == 0)
	   { t = t.substring(3);
	   }
      else
	   { i = t.indexOf("&id=");
	     if (i > 0) { t = t.substring(i+4); } else { t = ""; }
	   }
      if (t != "")
	   { i = t.indexOf("&");
	     if (i > 0) t = t.indexOf(0,i);
         }

	 if (t != 0) 
	   {  tfcfgViewID = t;
	      tfcfgViewType = 1;
	   }
      }

 	// set the language
   var mbox = document.getElementById("languagemenu");
   if (mbox) mbox.value = tfcfgLanguage;
	// Update the loginbox
   tfSetLoginBox();



}

function tfSetCookie(cookie,value) {
// If the value is empty, remove the cookie.
// set the expiration date for 30 days 
	var date = new Date();
	if (value != "") 
		{ date.setTime(date.getTime()+(30*24*60*60*1000)); }
	else
		{ date.setTime(date.getTime()-(24*60*60*1000)); }
	var expires = "; expires="+date.toGMTString();
	document.cookie = "TwitterFish"+cookie+"="+value+expires+"; path=/";
  }

function tfSetSessionCookie(cookie,value) {
// If the value is empty, remove the cookie.
// The cookie has no timeout, so only lasts for the session.
	if (value != "") { document.cookie = "TwitterFish"+cookie+"="+value+"; path=/"; }
  }

function tfGetCookie(cookie) {
	var nameEQ = "TwitterFish" + cookie + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) 
		  { return c.substring(nameEQ.length,c.length);
		  }
	}
      return "";
}

function BuildTwitterURL() {
   // Build the URl based on the viewID and viewType
  var url = "";
  var urlroot = "http://twitter.com/";
  var urlsuffix = ".json?callback=tfJsonGetStatus";

  if ( (tfcfgViewID == "_public") | (tfcfgViewID == "") )
  { 
	if (tfcfgUsername != "") {
		url="statuses/friends_timeline";
		// Also need to add login info.
		urlroot = 'http://' + tfcfgUsername + ':' + tfcfgPassword + '@twitter.com/';
    	}  else {
	    	url = "statuses/public_timeline"; 
    	}

  }
  else 
  { 
	url="statuses/user_timeline/" + tfcfgViewID;
  }
 return urlroot + url + urlsuffix;
}

function ChangeLanguage() {
  var mbox = document.getElementById("languagemenu");
  if (mbox) {
	tfcfgLanguage = mbox.value;
      tfSetCookie("language",tfcfgLanguage);
  }
  tfStatusReload();
}

function tfLogin(args) {
  var usr = args["TUname"];
  var pswd = args["TUpswd"];
  tfSetSessionCookie("userID", escape(usr + ":" + pswd));
  tfLoader();
}

function tfLogout() {
  tfSetCookie("userID","");
  tfLoader();
}

function tfSetLoginBox() {
  var box = document.getElementById("loginmenu");
  if (box) {
  	if (tfcfgUsername != "") {
		box.innerHTML = '<a href="javascript:tfLogout();">Logout</a>';
	} else {
		box.innerHTML = '<a href="javascript:dijit.byId(\'LoginDialog\').show();">Login</a>';
	}
  }
}

function tfShowHelp() {
  var box = dijit.byId('HelpDialog');
  box.titleNode.innerHTML = "Help";
  //box.setHref('twitterfishhelp.html');
  box.show();
}

function tfShowAbout() {
  var box = dijit.byId('AboutDialog');
  box.titleNode.innerHTML = "About";
  //box.setHref('twitterfishabout.html');
  box.show();
}

function tfAboutDialogClose() {
	alert("closing dialog...");
}

//================================================
//		Twitter Functions
//================================================

function tfTwitterStatus()
{
   var request = BuildTwitterURL();
   var aObj;
    // Create a new script object
    aObj = new JSONscriptRequest(request);
    // Build the script tag
    aObj.buildScriptTag();
    // Execute (add) the script tag
    aObj.addScriptTag();

}
function tfJsonGetStatus(data) {
  var t = '<table style="border:none;padding:2em;">';
  if (data != null)
	{
	  var wall = document.getElementById("statusbody");
	  var i = 0;
        var href;

        for (status in data)
        { t += "<tr>";
          i +=1;
          if (data[status].user != null) 
		{ 
		    href = '<a href="' + tfURL + '?id=' + data[status].user.screen_name + '">';
			 t += '<td>' + href + 
			  '<img width="48" height="48" src="' + data[status].user.profile_image_url + 
			  '" alt="' + data[status].user.name + '" border="0"></a>' +
					'</td>';
			 t += '<td class="StatusBlock">' +
				'<span class="UserName">' + href + data[status].user.name + 
				'</a></span><br/><div id="stat' + i.toString() + '">' +
				tfPendingStat(data[status].text) + '</div></td>';
			  tweets[i] = data[status].text;
		} else { t += '<td></td><td></td>'; }
	    t += '</tr>';
	  }
	  t += "</table>";
  	  wall.innerHTML = t;
	  tweetcount = i;

tfStatusChecker();

	}
  else
	{ alert("Empty JSON. Something went wrong...");
	};

}

function tfStatusReload() {
  var divbox;
  for (i=1;i<=tweetcount;i++) {
    divbox = document.getElementById("stat" + i);
    if (divbox) { divbox.innerHTML = tfPendingStat(tweets[i]); }
  }
  tfStatusChecker();

}

//================================================
//		Google Language Functions
//================================================

function tfStatusChecker() {
  var p;
  var d;

 tfDebugger("Checking " + tweetcount.toString() + " tweets");

 for (i=1;i<=tweetcount;i++) 
  { tfTranslate(i); };
}

function tfTranslate(target) {
    var text;
    text = tweets[target];
    tfDebugger("translating " + text);
    google.language.detect(text, tfDetect(target));
}


function tfDetect(i)  {
  var key = i;
  return function(result) {
    if (!result.error && result.language) {
	    tfDebugger("Language detected as " + result.language);
          if (result.language != tfcfgLanguage) 
		{ google.language.translate(tfStripBeforeTranslating(tweets[key]), result.language,tfcfgLanguage ,tfTranslated(key)); }
	    else
		{ tfDebugger ("No translation needed.");
		  var tbox = document.getElementById("stat"+key);
		  if (tbox) { tbox.innerHTML = tfActiveStat(tweets[key]); }
            }
		  
    } else {
	tfDebugger("detection failed for "+key);
    }
  }
}

function tfTranslated(i) {
  var key = i;
  return function(result) {
  var container;
  if (result.translation) { 
      container = document.getElementById("stat" + key.toString());
	if (!container) 
	  { tfDebugger("Cannot fetch div to post translation");
 	  }
	else
	  { container.innerHTML += "<br/>" + tfActiveStat(tfReplaceAfterTranslating(result.translation,tweets[key])); 
           tfDebugger("Translated as " + result.translation);
	  }
  } else {
	tfDebugger("translation failed.");
  }

  }
}

//================================================
//		Formatting Functions
//================================================

function tfActiveStat(t) {  return '<span class="StatusActive">' + tfAddLinks(t) + '</span>'; }
function tfPendingStat(t) {  return '<span class="StatusPending">' + t + '</span>'; }
function tfInitCap(t)
  { var retval = t;
    if (retval.length > 1)
      { retval = retval.substring(0,1) + retval.substring(1).toLowerCase();
      }
    retval = retval.replace(/_/g," - ");
    return retval;
  }

function tfStripBeforeTranslating(t) {
  var tmp = t;
  tmp = tmp.replace(/@ ?[\w]*/g,"@");
  return tmp;
}

function tfReplaceAfterTranslating(t,tw) {

  var tmp = t;
  var control = tw;
  var output = "";
  var result;
  var exp = /@/;
  var controlexp = /@ ?[\w]*/;
  var controlresult;

  while (tmp != '') {  
	result = exp.exec(tmp);
	if (result == null) {
		output += tmp;
		tmp = "";
	} else { 
		resultstr = result[0];
		output += tmp.substring(0,result.index);
		tmp = tmp.substring(result.index+resultstr.length);
		// Now fetch the actual user reference
		controlresult = controlexp.exec(control);
		if (controlresult) {
			output += controlresult[0];
			control = control.substring(controlresult.index+resultstr.length);
		} else {
			alert("Internal error. Cannot find user reference in tweet array.");
			output += '@ERROR';
		}	
	}

  }
  return output;
}


function tfAddLinks(t) {
var tmp = t;
  tmp = tfUrlRef(tmp);
  tmp = tfUserRef(tmp);
  return tmp;
}
   
function tfUserRef(t) {
// this routine finds username references and replaces them with links

  var tmp = t;
  var output = "";
  var result;
  var resultstr = "";
  var exp = /@ ?[\w]*/;

  while (tmp != '') {  
	result = exp.exec(tmp);
	if (result == null) {
		output += tmp;
		tmp = "";
	} else { 
		resultstr = result[0];
		output += tmp.substring(0,result.index);
		tmp = tmp.substring(result.index+resultstr.length);
		resultstr = ltrim(resultstr); 
		output += '@<a href="' + tfURL + '?id=' + resultstr + '">' + resultstr + '</a>';		
	}

  }
  return output;
}

function tfUrlRef(t) {
  //This routine identifies URls in the tweet and hotlinks them.
  var exp = /http:\/\/[^\s]*/;
  var tmp = t;
  var output = "";
  var result;
  var resultstr = "";

  while (tmp != '') {  
	result = exp.exec(tmp);
	if (result == null) {
		output += tmp;
		tmp = "";
	} else { 
		resultstr = result[0];
		output += tmp.substring(0,result.index);
		tmp = tmp.substring(result.index+resultstr.length);
		output += '<a href="' + resultstr + '" target="_new">' + resultstr + '</a>';		
	}

  }
  return output;

}

function ltrim(t) { return t.replace(/@\s*/, ''); }