var loggedIn=false;
var Url = {
 
	// public method for url encoding
	encode : function (string) {
		return escape(this._utf8_encode(string));
	},
 
	// public method for url decoding
	decode : function (string) {
		return this._utf8_decode(unescape(string));
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}


String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

			var since_id=0;
			var next_page=null;
	        var rpp = 100; //number of tweets to retrieve
			var active = false;
		        
			
			BitlyCB.shortenResponse = function(data) {
			    var s = '';
			    var first_result;
			    // Results are keyed by longUrl, so we need to grab the first one.
			    for     (var r in data.results) {
			            first_result = data.results[r]; break;
			    }
			    var old=$('textarea[name=text]').val();
			    $('textarea[name=text]').val(old+" "+first_result["shortUrl"].toString());
				updateCharCounter();
			    $('textarea[name=link]').val("");
			    $("#accordion").accordion( 'activate' , false) ;
			}
			
			BitlyCB.shortenReplace = function(data) {
			    var s = '';
			    var first_result,longUrl;
			    // Results are keyed by longUrl, so we need to grab the first one.
			    for (var r in data.results) {
			    	longUrl=r;
			        first_result = data.results[r]; break;
			    }
			    var old=$('textarea[name=text]').val();
			    old=old.replace(longUrl, data.results[longUrl]['shortUrl']);
			    $('textarea[name=text]').val(old);
				updateCharCounter();
			 }

			
			function SetCursorPosition(obj)
			{
				//FOR IE
				if(obj.setSelectionRange)
				{
					obj.focus();
					obj.setSelectionRange(obj.value.length,obj.value.length);
				}
				
				// For Firefox
				else if (obj.createTextRange)
				{
					var range = obj.createTextRange();
					range.collapse(true);
					range.moveEnd('character', obj.value.length);
					range.moveStart('character', obj.value.length);
					range.select();
				}
			}
			
			function ScrollToTweetBox(){
				 var theElement=document.getElementById("tweet_box");
				  var selectedPosX = theElement.offsetLeft;
				  var selectedPosY = theElement.offsetTop;
				  window.scrollTo(selectedPosX,0);
				  SetCursorPosition(theElement);	
			}

			
			function unescapeHTML(html) {
				var htmlNode = document.createElement("DIV");
				htmlNode.innerHTML = html;
				if(htmlNode.innerText !== undefined)
					return htmlNode.innerText; // IE
				return htmlNode.textContent; // FF
			} 
			
			function URLDecode(psEncodeString)
			{
				// Create a regular expression to search all +s in the string
			  var lsRegExp = /\+/g;
			  // Return the decoded string
			  return decodeURIComponent(psEncodeString).replace(lsRegExp, " ");
			}
			
			function utf8_encode(string) {
				string = string.replace(/\r\n/g,"\n");
				var utftext = "";
		 
				for (var n = 0; n < string.length; n++) {
		 
					var c = string.charCodeAt(n);
		 
					if (c < 128) {
						utftext += String.fromCharCode(c);
					}
					else if((c > 127) && (c < 2048)) {
						utftext += String.fromCharCode((c >> 6) | 192);
						utftext += String.fromCharCode((c & 63) | 128);
					}
					else {
						utftext += String.fromCharCode((c >> 12) | 224);
						utftext += String.fromCharCode(((c >> 6) & 63) | 128);
						utftext += String.fromCharCode((c & 63) | 128);
					}
		 
				}
		 
				return utftext;
			}

			function urlencode(str) {
				//var str0=Url._utf8_encode(str);
			var str0=utf8_encode(str)
	            return escape(str0).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
	        }        
			
			function boldify(m){
			     if (m.charAt(0)=='#' || m.charAt(0)=='@')
			    	 return '<b style="background:#8ADCFF">'+m+'<\/b>'
			     return m;
			}

			function stringToRegExp(str, flags){
			    return new RegExp(
			    		str.replace(/[\[\]\\{}()+*?.$^|]/g, function(m){return '\\'+m;}),flags);
			}

			
			function string_create_urls(input)
			{
			    return input
			    .replace(/(ftp|http|https|file):\/\/[\S]+(\b|$)/gim,
			'<a href="$&" class="my_link" target="_blank">$&</a>')
			    .replace(/([^\/])(www[\S]+(\b|$))/gim,
			'$1<a href="http://$2" class="my_link" target="_blank">$2</a>');
			} 
			
			function linkify (m){
				uname=m.substring(1);
				if (m.indexOf("/")>0)
					return "<a target=\"_blank\" rel=\"nofollow\" href=\"list/"+m+"\">"+m+"</a>";
				else
					return "<a target=\"_blank\" rel=\"nofollow\" href=\"http://twitter.com/"+uname+"\">"+m+"</a>";
			}
			
			function string_create_user_urls(input)
			{
				input=input.replace(/@[_a-zA-Z0-9\/-]+/g, linkify);
			    return input;
			} 
			
			
			
			function getTweets(data){
				var html="";
				 var term=$('input[name="search"]').val();
				 var ptrn=stringToRegExp(term, 'gi');
				 $.each(data.results, function(i,tweet){
					 var tweetText=string_create_urls(tweet.text);
					 tweetText = tweetText.replace(ptrn,boldify);
					 tweetText = string_create_user_urls(tweetText);
					 var loggedInPart='';
					 if (loggedIn){
						 loggedInPart='&nbsp;<a href="#" title="follow" id="follow" flw="'+tweet.from_user+'"><img src="images/add.png" style="width:10px;height:10px"/></a> ';
						 loggedInPart+='&nbsp;<a href="#" title="unfollow" id="unfollow" unflw="'+tweet.from_user+'"><img src="images/rmv.png" style="width:10px;height:10px"/></a> ';
					 }
					 var li='<li  style="display: none;" class="hentry status">\n';
					 li+='<span class="thumb vcard author"> <a class="url" target="_blank" href="http://twitter.com/'+tweet.from_user+'">';
					 li+='<img class="photo fn" rel="'+tweet.profile_image_url+'" width="48" height="48" src="'+tweet.profile_image_url+'" alt="'+tweet.from_user+'" /> ';
					 li+='</a><a href="#" title="info" id="info" info="'+tweet.from_user+'"><img src="images/i.png" style="width:10px;height:10px"/></a> '+loggedInPart+'</span> <span class="status-body"> <strong> <a class="screen-name" title="'+tweet.from_user+'" ';
					 li+='target="_blank" href="http://twitter.com/'+tweet.from_user+'">'+tweet.from_user+'</a> </strong>';
					 li+=' <span class="entry-content">'+tweetText+'</span>';
					 li+=' <span class="meta entry-meta"> <a class="entry-date" rel="bookmark" ';
					 li+='href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'" target="_blank">';
					 li+='<span class="published">'+tweet.created_at+'</span> </a> <span>';
					 li+='from '+unescapeHTML(tweet.source);	
					 li+='</span> </span> </span> <span class="actions">';
					 li+='<div> <a class="reply" strplyto="'+tweet.from_user+'" strplyid="'+tweet.id+'" target="_blank" title="reply to '+tweet.from_user+'" href="http://twitter.com/home?status=@'+tweet.from_user+'%20&in_reply_to_status_id='+tweet.id+'&in_reply_to='+tweet.from_user+'">&nbsp; </a></div>';
					 var rtt=urlencode(unescapeHTML("RT:@"+ tweet.from_user+" "+tweet.text));
					 var href="http://twitter.com/home?status="+rtt;
					 li+='<div> <a class="rt" title="Retweet" target="_blank" strt="'+rtt+'" href="'+href+'" >&nbsp; </a></div></span></li>';
					 html+=li;
				 });
				 return html;
			}
			
			function doSearch(){
				{
					$("#more").hide();
					var demos = $("div.wrapper div.tweetsbox");
					 $("#message").html("&nbsp;");
					 $("#progressbar").show();
					 $('.hiddenlist').empty();
					 $('.statuses',demos).empty();
					 stopUpdates();
					  var query = urlencode($('input[name="search"]').val()); //what to search for
						 $.getJSON('http://search.twitter.com/search.json?callback=?&q='+query+'&rpp='+rpp+'&result_type=recent', function (data){
							 
							 if (typeof data.error!='undefined'){
								 $("#progressbar").hide();
								 $("#message").html("invalid query");
								 since_id=0;
								 $("#progressbar").hide();
								 resumeUpdates();
								 return;
							}
							 
							 if (typeof data.next_page =='undefined'){
								 $("#more").hide();
								 next_page=null;
							 }
							 else{
								 $("#more").show();
								 next_page=data.next_page;
							 }
							 if (data.results.length==0){	
								 $("#progressbar").hide();
								 $("#message").html("No Tweets Found for this search!");
								 since_id=0;
								 resumeUpdates();
								 return;
							 }
							 since_id=data.refresh_url;
							$('.hiddenlist').html(getTweets(data));
							$('.hiddenlist li').each(function(){
								$(this).hide();
								$('.statuses',demos).append($(this));
								$('a.reply',$(this)).each(function(){
								 	$(this).click(function(event){
									 if ($("#statusupdt").length > 0 && $(this).attr('strplyto')!=undefined ) {
										 event.preventDefault();
										 $("input[name=in_reply_to_status_id]").val($(this).attr('strplyid'));
										 $("input[name=in_reply_to]").val($(this).attr('strplyto'));
										 newText="@"+$(this).attr('strplyto')+" "+$("textarea[name=text]").val();
										 $("textarea[name=text]").val(newText);
										 ScrollToTweetBox();
										 updateCharCounter();
									}
								 	});
								 });
								$('a.rt',$(this)).each(function(){
								 	$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('strt')!=undefined ) {
											 event.preventDefault();
											 $("input[name=in_reply_to_status_id]").val("");
											 $("input[name=in_reply_to]").val("");
											 newText= unescapeHTML(URLDecode($(this).attr('strt')));
											 $("textarea[name=text]").val(newText);
											 ScrollToTweetBox();
											 updateCharCounter();
										}
									 	});
									});
								$('#follow',$(this)).each(function(){
									$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('flw')!=undefined ) {
											 event.preventDefault();
											 follow( $(this).attr('flw'));
										}
									 });
								});
								
								$('#unfollow',$(this)).each(function(){
									$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('unflw')!=undefined ) {
											 event.preventDefault();
											 unfollow( $(this).attr('unflw'));
										}
									 });
								});
								
								$('#info',$(this)).each(function(){
									$(this).click(function(event){
										 event.preventDefault();
										 info( $(this).attr('info'));
									 });
								});
								
								$(this).show();
							});
							
							
							 $("#progressbar").hide();
							 $("#message").html("&nbsp;");
							 resumeUpdates();
					});
				 }
			}
			
			function doMore(){
				{
					var demos = $("div.wrapper div.tweetsbox");
						$('.hiddenlist').empty();
						var url='http://search.twitter.com/search.json?callback=?&result_type=recent&'+next_page.substring(1);
						$("#more").addClass("loading").html("");
						stopUpdates();
						 $.getJSON(url, function (data){	
							 
							 if (typeof data.error!='undefined'){
								 $("#more").addClass("loading").html("");
								 $("#more").blur();
								 resumeUpdates();
								 return;
							}
							 
							 if (typeof data.next_page =='undefined'){
								 $("#more").hide();
								 next_page=null;
							 }
							 else{
								 $("#more").show();
								 next_page=data.next_page;
							 }
							 if (data.results.length==0){	
								 $("#more").addClass("loading").html("");
								 $("#more").blur();
								 resumeUpdates();
								 return;
							 }
							 since_id=data.refresh_url;
							$('.hiddenlist').html(getTweets(data));
							$('.hiddenlist li').each(function(){
								$(this).hide();
								$('.statuses',demos).append($(this));
								$('a.reply',$(this)).each(function(){
								 	$(this).click(function(event){
									 if ($("#statusupdt").length > 0 && $(this).attr('strplyto')!=undefined ) {
										 event.preventDefault();
										 $("input[name=in_reply_to_status_id]").val($(this).attr('strplyid'));
										 $("input[name=in_reply_to]").val($(this).attr('strplyto'));
										 newText="@"+$(this).attr('strplyto')+" "+$("textarea[name=text]").val();
										 $("textarea[name=text]").val(newText);
										 ScrollToTweetBox();
										 updateCharCounter();
									}
								 	});
								 });
								$('a.rt',$(this)).each(function(){
								 	$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('strt')!=undefined ) {
											 event.preventDefault();
											 $("input[name=in_reply_to_status_id]").val("");
											 $("input[name=in_reply_to]").val("");
											 newText= unescapeHTML(URLDecode($(this).attr('strt')));
											 $("textarea[name=text]").val(newText);
											 ScrollToTweetBox();
											 updateCharCounter();
										}
									 	});
									});
								$('#follow',$(this)).each(function(){
									$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('flw')!=undefined ) {
											 event.preventDefault();
											 follow( $(this).attr('flw'));
										}
									 });
								});
								
								$('#unfollow',$(this)).each(function(){
									$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('unflw')!=undefined ) {
											 event.preventDefault();
											 unfollow( $(this).attr('unflw'));
										}
									 });
								});
								
								$('#info',$(this)).each(function(){
									$(this).click(function(event){
										 event.preventDefault();
										 info( $(this).attr('info'));
									 });
								});
								
								$(this).show();
								});
							$("#more").removeClass("loading").html("Older Tweets");
							resumeUpdates();
						});
				 }
			}
			
				
			function stopUpdates(){
				var demos = $("div.wrapper div.tweetsbox");
				 active=false;
				 $('.statuses',demos).stopTime('controlled');
			}
			
			function resumeUpdates(){
				if (!active){
					active=true;
					doTimer();
				}
			}
			function doTimer(){
				$(function() { 	
					var demos = $("div.wrapper div.tweetsbox");
					  $('.statuses',demos).everyTime(20000, 'controlled', function() {
						$.getJSON('http://search.twitter.com/search.json'+since_id+'&callback=?',function (data){
								$('.hiddenlist').empty();
								since_id=data.refresh_url;
								$('.hiddenlist').html(getTweets(data));
								$('.hiddenlist li').each(function(){
									$(this).hide();
									$('.statuses',demos).prepend($(this));
									$('a.reply',$(this)).each(function(){
									 	$(this).click(function(event){
										 if ($("#statusupdt").length > 0 && $(this).attr('strplyto')!=undefined ) {
											 event.preventDefault();
											 $("input[name=in_reply_to_status_id]").val($(this).attr('strplyid'));
											 $("input[name=in_reply_to]").val($(this).attr('strplyto'));
											 newText="@"+$(this).attr('strplyto')+" "+$("textarea[name=text]").val();
											 $("textarea[name=text]").val(newText);
											 ScrollToTweetBox();
											 updateCharCounter();
										}
									 	});
									 });
									$('a.rt',$(this)).each(function(){
									 	$(this).click(function(event){
											 if ($("#statusupdt").length > 0 && $(this).attr('strt')!=undefined ) {
												 event.preventDefault();
												 $("input[name=in_reply_to_status_id]").val("");
												 $("input[name=in_reply_to]").val("");
												 newText=unescapeHTML( URLDecode($(this).attr('strt')));
												 $("textarea[name=text]").val(newText);
												 ScrollToTweetBox();
												 updateCharCounter();
											}
										 	});
										});
									$('#follow',$(this)).each(function(){
										$(this).click(function(event){
											 if ($("#statusupdt").length > 0 && $(this).attr('flw')!=undefined ) {
												 event.preventDefault();
												 follow( $(this).attr('flw'));
											}
										 });
									});
									
									$('#unfollow',$(this)).each(function(){
										$(this).click(function(event){
											 if ($("#statusupdt").length > 0 && $(this).attr('unflw')!=undefined ) {
												 event.preventDefault();
												 unfollow( $(this).attr('unflw'));
											}
										 });
									});
									
									$('#info',$(this)).each(function(){
										$(this).click(function(event){
											 event.preventDefault();
											 info( $(this).attr('info'));
										 });
									});
									
									$(this).show(500);
									});
							});
				});});
			}
			
			function deleteSearch(delId){
				 $.ajax({
						url:'/srch',
						type: "POST",
						cache:false,
						data : {'op':'destroy', 'p': delId} , 
						success : function (data){
						 if (data.indexOf("success")==0){
							 var selector='#'+delId;
							 $(selector).remove();
							 if ($('#searches .srch').length==0)
								 $('#searches').remove();
						 }
					}
				 });
			}
			
			function updateCharCounter(){
				 if ( $("#statusupdt").length > 0 ) {
						elem=$('textarea[name=text]');
							if ($(elem).val().length==0){
								$('input[name=post]').attr('disabled','disabled');
								$("input[name=in_reply_to_status_id]").val("");
								$("input[name=in_reply_to]").val("");
							}
					        var max = 140;
					        var diff=max - $(elem).val().length;	
					        counter= $(elem).parent().find('.char-counter')
					        $(counter).html(diff);
					        if (diff<0 ||  diff==140){
					        	 $('input[name=post]').attr('disabled','disabled');
					        	if(diff<0)
					        		$(counter).css('color','red');
					        	else
					        		$(counter).css('color','rgb(204, 204, 204)');
					        }
					        else {
					        	 $('input[name=post]').removeAttr('disabled');
					        	 $(counter).css('color','rgb(204, 204, 204)');
					        }
					   
					 }			
			}
			
			function updateTrends(){
				$.getJSON('http://api.twitter.com/1/trends/current.json?callback=?',function (data){
					 if (typeof data.error=='undefined'){
						 $.each(data.trends, function(key, value){
							if (key.indexOf("2")==0){
								$("#trends").empty();
								var elem=$("#trends");
								$.each(value,function(i,query){
									 elem.append("<a class=\"q\" href=\""+urlencode(query.query)+"\">"+query.name+"</a><br/>");
								});
								$('a', elem).click(function(event){
									 event.preventDefault();
									 $("#queries").val("");
									 $('input[name="search"]').val(URLDecode($(this).attr('href')));
									 doSearch();
								 });
							}
						 }); 
					 }
				 });
			}
			
			function updateSearches(){
				 $.ajax({
						url:'/srch',
						type: "POST",
						cache:false,
						data : {'op':'get'} , 
						success : function (data){
						 if (data.trim().length==0){
							 $('#savedSearch').empty();
						 }
						 else if (data.indexOf("error")==0 ){
							 alert(data);
						 }
						 else{
							 $('#savedSearch').html(data);
							 $('.sl').click(function (event){
								 event.preventDefault();
								 $("#queries").val("");
								 $('input[name="search"]').val(URLDecode($(this).attr('href')));
								 doSearch();
							 });
							 $('.rmvs').click(function (event){
								 event.preventDefault();
								 deleteSearch($(this).attr('sid'));
							 });
						 }
					}
				 });
		}
			

			function autoShort(){
				if ($("#autoshort").html()=="on"){
					var newtext=$('textarea[name=text]').val();
					var urlRegExp = new RegExp(/(https?:\/\/\S+)/igm);							
					var urlMatches = newtext.match(urlRegExp);
					if (!(!urlMatches)){
						for (var i=0; i < urlMatches.length; i++) {  
							var url = urlMatches[i].trim();
							if (url.length>30){
								BitlyClient.shorten(url, 'BitlyCB.shortenReplace');
							}
						}
					}
				}
			}
			
			function follow(screenName){
				$.ajax({
					url : '/flw',
					type: 'POST',
					data : {'op':'follow', 'p': screenName} , 
					datatype :'html',
					success : function (data){
						if (data.substr(0,7)=="expired"){
							alert("Your session expired, please sign in again.");
							location.reload();
						}
						else {
							modal("follow : "+screenName,data);
						}
					}});
			}
			
			function unfollow(screenName){
				$.ajax({
					url : '/flw',
					type: 'POST',
					data : {'op':'unfollow', 'p': screenName} , 
					datatype :'html',
					success : function (data){
						if (data.substr(0,7)=="expired"){
							alert("Your session expired, please sign in again.");
							location.reload();
						}
						else {
							modal("unfollow : "+screenName,data);
						}
					}});
			}
			
			function info(screenName){
				$.ajax({
					url : '/flw',
					type: 'POST',
					data : {'op':'info', 'p': screenName} , 
					datatype :'html',
					success : function (data){
						if (data.substr(0,7)=="expired"){
							alert("Your session expired, please sign in again.");
							location.reload();
						}
						else {
							modal("Info : "+screenName,data);
						}
					}});
			}
			

			
		$(document).ready(function(){
			
			loggedIn=  $("#statusupdt").length > 0;
			$(function() {
				$("#progressbar").progressbar({
					value: 100
				});
			});
			
			 $(function() {
					$("#accordion").accordion({
						collapsible: true,
						active: false,
						animated:false
					});
				});
			 
				if ($("#autoshort").html()=="on")
					$("#accordion").hide();


			$(".adds").click(function(event){
				var s=$('input[name="search"]').val();
				if (s.trim()!=""){
					var se= urlencode(s);
					var selector='a.sl[href="'+se+'"]';
					if ($(selector).length==0){
						$.ajax({
							url:'/srch',
							type: "POST",
							cache:false,
							data : {'op':'create', 'p': s} , 
							success : function (data){
							 if (data.indexOf("error")==0){
								 alert(data);
							 }
							 else {
								if ($('#savedSearch #searches').length==0){ 
									$('#savedSearch').html("<div id=\"searches\"><div class=\"hsrch\">Saved Searches</div></div>");
								}
								$('#searches').append(data);
								$('.sl').unbind('click');
								$('.rmvs').unbind('click');
								$('.sl').click(function (event){
									 event.preventDefault();
									 $("#queries").val("");
									 $('input[name="search"]').val(URLDecode($(this).attr('href')));
									 doSearch();
								 });
								 $('.rmvs').click(function (event){
									 event.preventDefault();
									 deleteSearch($(this).attr('sid'));
								 });
							 }
						}
					 });					
					}
				}
			});	

			 $("#queries").change(function () {
				 var searchterm=$("#queries option:selected").val();
				 if (searchterm.length>0){
					 $('input[name="search"]').val(searchterm);
					 doSearch();
				 }
		        });	
			
			var demos = $("div.wrapper div.tweetsbox");
			$('input[name="search"]').keypress( function(e){
				 if (e.which == 10 || e.which == 13)
					 doSearch();
			
			});
			
			 $("#go").click(function(event){
				doSearch();
			 });
			 
			 $("#more").click(function(event){
				 event.preventDefault();
				 doMore();
			 });
	            
			 $("#message").html("&nbsp;");   
			 $("#progressbar").show();
			 $("#more").hide();
			 var qindex=window.location.href.indexOf("?");
			 if (qindex>0){
				 var q=window.location.href.substr(qindex+1);
				 q=q.substr(q.indexOf('=')+1);
				 $('input[name="search"]').val(URLDecode(q));
			 }
			 else  $('input[name="search"]').val("tunisie");
			 doSearch();
			 
			 updateTrends();
			 $('#trends').everyTime(900000, 'controlled', function() {updateTrends();});
			
			 updateSearches();
			 $('#savedSearch').everyTime(900000, 'controlled', function() {updateSearches();});
			 
			 $("input[name=post]").click(function(event){
				 $.ajax({
						url:'/tweet',
						type: "POST",
						cache:false,
						data : {'text': $("textarea[name=text]").val() , 
								'in_reply_to_status_id': $("input[name=in_reply_to_status_id]").val(),
								'in_reply_to': $("input[name=in_reply_to]").val()
								}, 
						error : function (){$("#tweeting").attr("src","none.gif");alert("unexpected error while trying to submit your tweet.\n The server may be down.")},
						beforeSend:function(){$("#tweeting").attr("src","ajax.gif")},
						success : function (data){
						if (data.length>0)
						{
							if (data.substr(0,7)=="expired"){
								alert("Your session expired, please sign in again.");
								location.reload();
								$("#tweeting").attr("src","none.gif");
							}
							else if (data.substr(0,7)=="success"){
								$('input[name=post]').attr('disabled','disabled');
								$("input[name=in_reply_to_status_id]").val("");
								$("input[name=in_reply_to]").val("");									
								$("textarea[name=text]").val("");		
								updateCharCounter();
								setTimeout('$("#tweeting").attr("src","none.gif")',2000);
							}
							else {
								alert(data);
								$("#tweeting").attr("src","none.gif");
							}
						}
					}
				});
			});
			 
			 $('textarea[name=text]').keyup(function(){
			        counter= $(this).parent().find('.char-counter')
					if ($(this).val().length==0){
						$('input[name=post]').attr('disabled','disabled');
						$("input[name=in_reply_to_status_id]").val("");
						$("input[name=in_reply_to]").val("");
			        	$(counter).css('color','rgb(204, 204, 204)');
					}else {
						autoShort();
					}

			        var max = 140;
			        var diff=max - $(this).val().length;	
				        $(counter).html(diff);
			        if (diff<0 ||  diff==140 ){
			        	 $('input[name=post]').attr('disabled','disabled');
			        	 if (diff<0 )
			        		 $(counter).css('color','red');
			        }
			        else {
			        	 $('input[name=post]').removeAttr('disabled');
			        	 $(counter).css('color','rgb(204, 204, 204)');
			        }
			   });
			 
			 $("#autoshort").click(function(event){
				 event.preventDefault();
				 if ($(this).html()=="off"){
					 $(this).html("on");
					 $("#accordion").hide();
					 autoShort();
				 }
				 else {
					 $("#accordion").show();
					 $(this).html("off");
				 }
			 });
			 
			 $("#yaml").click(function(event){
				 event.preventDefault();
				 if ($(this).html()=="off"){
					 $(this).attr('dir','rtl');
					 $(this).html("on");
					 Yamli.yamlify('tweet_box',{
	        				uiLanguage:'en',
	        				settingsPlacement:'hide',
	        				startMode:'on',
	        				uiFontFamily:'"Lucida Grande",sans-serif',
	        				settingsLinkColor:'#0084b4'}
			        	);

				 }
				 else {
					 Yamli.deyamlify('tweet_box');
					 $(this).html("off");
					 $(this).attr('dir','ltr');
				 }
			 });
			 
			 $("#nav").corner("keep");

		});
