
imgs=null;  // needed because you call changeBg() from script tags if you moved to initgrid() you could eliminate

function setLocalTrendsTop5(woeid) {
    url = 'http://api.twitter.com/1/trends/' + woeid + '.json?callback=?';

    $.getJSON(url, function(data) {
       for (i=0; i < data[0].trends.length && i <= 4 ; i++) {
         $('#localTrend' + (i+1)).html(data[0].trends[i].name);
        }
   });

}

function getTwitterAvailablePlaces(latitude, longitude, closest) {

    url = 'http://api.twitter.com/1/trends/available.json?lat=' + latitude + '&long=' + longitude + '&callback=?';

    $.getJSON(url, function(data) {
      
          setLocalTrendsTop5(data[0].woeid);
  });
	
};


function setLocalTrends() { 
    if (geo != null) {
      var pos = geo.getPosition();
      getTwitterAvailablePlaces(pos.lat,pos.long,geo.getLocation().city);
    }

}

function kminit() {

tweetsJSON = null;





if (typeof(tweeters_all) != "undefined") {

  tweetsJSON = tweeters_all;

}



tweetsIMG = null;

if (typeof(img_all) != "undefined") {

  tweetsIMG = img_all;

}



currentTweet = new Array();

divTimeNames = new Array();

divTweetNames = new Array();

divTweeterNames = new Array();

divTrends = new Array();

imgs = new Array();

currentDivId = -1;



if (tweetsIMG != null) {

  for (i=0; i < tweetsIMG.img.length; i++) {

      imgs[i] = tweetsIMG.img[i]; 

  }

}



if (tweetsJSON != null) {

  for (i=0; i < tweetsJSON.tweeters.length; i ++) {

     currentTweet[i] = 0;

     divTimeNames[i] = 'grid' + i + '-time';

     divTweetNames[i] = 'grid' + i + '-tweet';

     divTweeterNames[i] = 'grid' + i + '-tweeter';

  }

  

}



changeBg('image-2',1);

}



function getNextTweet(id) {

    curTweet = currentTweet[id];

    formIdTweet = divTweetNames[id];

    formIdTime = divTimeNames[id]; 

    if (curTweet+1 < tweetsJSON.tweeters[id].tweets.length) {

        currentTweet[id] = currentTweet[id] + 1;

        curTweet = currentTweet[id];

        setTweet(formIdTweet,id,curTweet); 

 $('#'+formIdTime).html(relative_time(tweetsJSON.tweeters[id].tweets[curTweet].time));



     }

}



function css_browser_selector(u){var ua = u.toLowerCase(),is=function(t){return ua.indexOf(t)>-1;},g='gecko',w='webkit',s='safari',o='opera',h=document.getElementsByTagName('html')[0],b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?('ie ie'+RegExp.$1):is('firefox/2')?g+' ff2':is('firefox/3.5')?g+' ff3 ff3_5':is('firefox/3')?g+' ff3':is('gecko/')?g:is('opera')?o+(/version\/(\d+)/.test(ua)?' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?' '+o+RegExp.$2:'')):is('konqueror')?'konqueror':is('chrome')?w+' chrome':is('iron')?w+' iron':is('applewebkit/')?w+' '+s+(/version\/(\d+)/.test(ua)?' '+s+RegExp.$1:''):is('mozilla/')?g:'',is('j2me')?'mobile':is('iphone')?'iphone':is('ipod')?'ipod':is('mac')?'mac':is('darwin')?'mac':is('webtv')?'webtv':is('win')?'win':is('freebsd')?'freebsd':(is('x11')||is('linux'))?'linux':'','js']; c = b.join(' '); h.className += ' '+c; return c;}; css_browser_selector(navigator.userAgent);



function getPrevTweet(id) {

    curTweet = currentTweet[id];

    formIdTweet = divTweetNames[id];

    formIdTime = divTimeNames[id]; 

     if (curTweet > 0) {

        currentTweet[id] = currentTweet[id] -1;

        curTweet = currentTweet[id];

        setTweet(formIdTweet,id,curTweet);

        

  $('#'+formIdTime).html(relative_time(tweetsJSON.tweeters[id].tweets[curTweet].time));

     }

}



// HERE IS TWITTER's REGEX

// .replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="'+url+'">'+url+'</a>'; })





function relative_time(time_value) {



    var values = time_value.split(" ");

    if (isTrends) {

 time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];

    } else {

    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];

    }



    var parsed_date = Date.parse(time_value);

    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();



    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);

    delta = delta + (relative_to.getTimezoneOffset() * 60);



    if (delta < 60) {

	return 'less than a minute ago';

    } else if(delta < 120) {

	return 'about a minute ago';

    } else if(delta < (60*60)) {

	return (parseInt(delta / 60)).toString() + ' minutes ago';

    } else if(delta < (120*60)) {

	return 'about an hour ago';

    } else if(delta < (24*60*60)) {

	return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';

    } else if(delta < (48*60*60)) {

	return '1 day ago';

    } else {

	return (parseInt(delta / 86400)).toString() + ' days ago';

    }

}





function initGridBox(id) {



    tweetDivId = divTweetNames[id];

    timeDivId = divTimeNames[id]; 

    tweeterDivId = divTweeterNames[id];







    setTweet(tweetDivId,id,0,true);

 

    if (tweetsJSON != null) {



       if (isTrends) {

         $('#'+tweeterDivId).html(tweetsJSON.tweeters[id].tweets[0].screenName);

       } else {

         $('#'+tweeterDivId).html(tweetsJSON.tweeters[id].name);

       }





         $('#'+timeDivId).html(relative_time(tweetsJSON.tweeters[id].tweets[0].time));

       

       tweeter = tweetsJSON.tweeters[id].name;

       $('#ATempTitleDiv').html(tweeter); 



       fontSize=17;

       $('#ATempTitleDiv').css('font-size',fontSize+'px'); 

       $('#ATempTitleDiv').css('font-family','Lucida Grande, Arial,Verdana,sans-serif'); 

       while ($('#ATempTitleDiv').width() > 162) {

          fontSize = fontSize -.3;

          $('#ATempTitleDiv').css('font-size',fontSize+'px');       

       }

       $('#'+tweeterDivId).css('font-size',fontSize+'px');    

    }

}







function setTweet(tweetDivId, tweeterId, tweetId,isInit) {

  



      tweet =  tweetsJSON.tweeters[tweeterId].tweets[tweetId].tweet;



      tweet = tweet.replace( /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,"<a href=\"$1\" target=\"_blank\">$1</a>" )

      

      fontSize = 23;

      lineHeight = 24.5;

      if (isTrends) {

         maxHeight=88;

      } else {

        maxHeight =109;

     }

      decrementFont = .2;

      if (navigator.appVersion.indexOf("Win") != -1 ) {

        

          $('#ATempDiv').css('font-weight','bold');

        

         decrementFont = 1;

      }

     

       $('#ATempDiv').css('font-size',fontSize + 'px'); 

       $('#ATempDiv').css('line-height',lineHeight +'px'); 

       $('#ATempDiv').css('font-family','Helvetica,Lucida Grande,Arial,Verdana,sans-serif'); 

       $('#ATempDiv').html(tweet);



      while ($('#ATempDiv').height() > maxHeight) {



           fontSize = fontSize - decrementFont;

           lineHeight = fontSize + 1.3;  

           $('#ATempDiv').css('font-size',fontSize + 'px');            

           $('#ATempDiv').css('line-height',lineHeight +'px');   

           $('#ATempDiv').html(tweet);     

      }  

 

      if (isTrends) {

        tweeterDivId = divTweeterNames[tweeterId];

        $('#'+tweeterDivId).html(tweetsJSON.tweeters[tweeterId].tweets[tweetId].screenName);

     

      }

      if (typeof(isInit) == "undefined"  )  {   



         $('#'+tweetDivId).css('font-size',fontSize+'px');  

         $('#'+tweetDivId).css('line-height',lineHeight+'px');

         $('#'+tweetDivId).html(tweet);
     }
     
          followButtonId = '#grid' +tweeterId + '-mygrid' +  ' #' + 'follow' + tweeterId + 'Button';
          mentionButtonId = '#grid' +tweeterId + '-mygrid' +  ' #' + 'mention' + tweeterId + 'Button';
          infoButtonId = '#grid' +tweeterId + '-mygrid' +  ' #' + 'info' + tweeterId + 'Button';
          myGridButtonId = '#grid' +tweeterId + '-mygrid' +  ' #' + 'myGrid' + tweeterId + 'Button';
          retweetButtonId = '#grid' +tweeterId + '-mygrid' +  ' #' + 'retweet' + tweeterId + 'Button';

          if (isTrends) {
      	    $(followButtonId).attr('title','Follow @' + tweetsJSON.tweeters[tweeterId].tweets[tweetId].screenName);
	    $(mentionButtonId).attr('title','Mention @' + tweetsJSON.tweeters[tweeterId].tweets[tweetId].screenName);
          } else {
	      $(followButtonId).html("fol");
	    $(followButtonId).attr('title','Follow ' + tweetsJSON.tweeters[tweeterId].name + ' on Twitter');
	    $(mentionButtonId).attr('title','Mention ' + tweetsJSON.tweeters[tweeterId].name + ' on Twitter');
	    $(infoButtonId).attr('title','Twitter profile of ' + tweetsJSON.tweeters[tweeterId].name);
	  }
 	 $(followButtonId).tipTip({maxWidth: "300px"});
         $(mentionButtonId).tipTip({maxWidth: "300px"});
 	 $(infoButtonId).tipTip({maxWidth: "300px"});
         $(myGridButtonId).tipTip({maxWidth: "300px"});
 	 $(retweetButtonId).tipTip({maxWidth: "300px"});
}



function initGrid() {



   if (tweetsJSON != null) {

      numTweeters = tweetsJSON.tweeters.length;

      for (i=0; i < numTweeters; i ++) {

         initGridBox(i);

      }

   }



 if (tweetsJSON == null) {

     numTweeters = 0;

 }

 



      if (numTweeters < 20) {



         for (j=numTweeters; j < 20; j++) {

   

              $('#grid' +j+ '-mygrid').css('display','none');

               $('#grid' +j+ '-follow').css('display','none');   

              $('#thegrid #grid' +j+ ':hover').css('border','solid 2px');

              $('#thegrid #grid' +j+ ':hover').css('border-color','#e7e7e7');

             $('#thegrid #grid' +j+ ':hover').css('margin','1px');

              
              $('#thegrid #grid' +j).hover( function(){

                       $(this).css('background-color', '#1c1c1c');
           
               });

        
         }

      }   


 



      if (sort == 'f') {

        $('#sortFollowers').css('text-decoration','underline');
          $('#sortFollowers').css('color','#33ccff');
        $('#sortFollowers a').css('color','#33ccff');

      } else if ((sort == 'latest') || (sort == 'l')) {

        $('#sortLastTweet').css('text-decoration','underline');
        $('#sortLastTweet').css('color','#33ccff');
        $('#sortLastTweet a').css('color','#33ccff');

      } else if (sort == 's') {

        $('#sortABC').css('text-decoration','underline');
        $('#sortABC a').css('color','#33ccff');
        $('#sortABC').css('color','#33ccff');
      }



      for (var i=1; i <= totalNumberPages; i++) {

        basePage = $('#gotopage' + i).attr('href');
        var baseIdx = basePage.lastIndexOf('/');
        basePage = basePage.substring(baseIdx);
             
  
        if (sort == 'latest') { 
         //  $('#gotopage' + i).attr('href', '/twitter' + basePage);
          
       } else {
             idx = basePage.lastIndexOf('-');
             endIdx = basePage.lastIndexOf('.');
            iterPage = basePage.substring(idx+1,endIdx);
            pageNoExt = basePage.substring(0,idx) + ".html";
    
       $('#gotopage' + i).attr('href', '/twitter/' + sort + '/' + iterPage +   pageNoExt);
       }


      }

      $('#gotopage' + page).css('color','#33bbff');





}



function initTrends() {

      isTrends = true;

      numTrends = tweetsJSON.tweeters.length;

      for (i=0; i < numTrends; i ++) {

         $('#trend' + i + ' h1').html(tweetsJSON.tweeters[i].name);

      }

      for (i=1; i <= top10.hour.length; i++) {

         setResizedTrend('hourly',i,top10.hour[i-1]);

         setResizedTrend('daily',i,top10.daily[i-1]);

         setResizedTrend('weekly',i,top10.weekly[i-1]);

      }

}



function setResizedTrend(type,id,trend) {





    $('#top5TempDiv').html(trend);

    $('#top5TempDiv').css('font-family','Lucida Grande,Arial,Helvetica,Verdana,sans-serif');

    fontSize = 16;

    $('#top5TempDiv').css('font-size',fontSize+'px');



    while ($('#top5TempDiv').width() > 122) {

        fontSize = fontSize - .3;     

        $('#top5TempDiv').css('font-size',fontSize+'px');

    }

    $('#' + type + 'Trend' + i).css('font-size',fontSize+'px');

    $('#' + type + 'Trend' + i).html(trend);

}





function setCurrentDiv(id) {

   currentDivId = id;

}



function changeBg(id, img) { 

if (isTrends) {

if (document.getElementById(id) != null) {
    document.getElementById(id).style.backgroundImage = "url(/images/trendsbg.png)";
  }

} else {

  if (imgs != null) {

     document.getElementById(id).style.backgroundImage = "url(" + imgs[img] + ")";
     
  }

}

}



var addthis_share = 

{ 

// ...

    templates: {

                   twitter: 'Found better way of reading tweets: twitgrids.com (from @twitgrids)',

                   blogger: '{{html}} <br /> From <a href="{{url}}">{{title}}</a> at Example.com'

               }

}



$(document).ready(function() {	



       $('a[name=refresh]').click(function(e) { 

          refreshStats();

       });



	//select all the a tag with name equal to modal

	$('a[name=modal]').click(function(e) {  

		//Cancel the link behavior

		e.preventDefault();

		

		//Get the A tag

		var id = $(this).attr('href');

	

		//Get the screen height and width

		var maskHeight = $(document).height();

		var maskWidth = $(window).width();

	

		//Set heigth and width to mask to fill up the whole screen

		$('#mask').css({'width':maskWidth,'height':maskHeight});

		

		//transition effect		

		$('#mask').fadeIn(1000);	

		$('#mask').fadeTo("slow",0.8);	

	

		//Get the window height and width

		var winH = $(window).height()+(window.pageYOffset*2);

		var winW = $(window).width();

              

		//Set the popup window to center

		$(id).css('top',  winH/2-$(id).height()/2);

		$(id).css('left', winW/2-$(id).width()/2);

	

		//transition effect



		$(id).fadeIn(400); 

	

	});

	

	//if close button is clicked

	$('.window .close').click(function (e) {

		//Cancel the link behavior

		e.preventDefault();

		

		$('#mask').hide();

		$('.window').hide();

	});		

	

	//if mask is clicked

	$('#mask').click(function () {

		$(this).hide();

		$('.window').hide();

	});			

	

});





// KM BEGIN



function openLightbox() {



	$("#dialogPOST").css('visibility', 'visible');

	//$("#dialogPOST").css('display', 'block');

}



function closeLightbox() {



	$("#dialogPOST").css('visibility', 'hidden');

	//$("#dialogPOST").css('display', 'none');

}



function displayYouMustSignInLightbox() {
   
     var maskHeight = $(document).height();
     var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height()+(window.pageYOffset*2);
		var winW = $(window).width();
              
		//Set the popup window to center
		$("#youMustSignInLightbox").css('top',  winH/2-$("#youMustSignInLightbox").height()/2);
		$("#youMustSignInLightbox").css('left', winW/2-$("#youMustSignInLightbox").width()/2);
	
$("#youMustSignInLightbox").fadeIn(400); 
	$("#youMustSignInLightbox").css('visibility', 'visible');
}

function setMyGridEmptyLightboxText() {
$("#dialogMyGridEmpty span.mgfTitle").html("MyGrid is empty!");
$("#dialogMyGridEmpty span.mgfInfo").html("Your MyGrid is empty.  <P>To add tweeters to MyGrid, click +My on the popup controls.<P>MyGrid changes are automatically saved.");
}

function setMyGridEmptyNotLoggedInText() {
$("#dialogMyGridEmpty span.mgfTitle").html("Sign in to use MyGrid!");
$("#dialogMyGridEmpty span.mgfInfo").html("To build your custom Twitter grid, you must first <a href=\"/action/twitter_sign_in\">sign in</a> with Twitter.");
}

var showMyGrid=false;

function displayMyGridEmptyLightboxIfNecessary() {

 if (typeof(SESSION_INFO) != "undefined") {
    if (SESSION_INFO.have_oauth == 0) {
        setMyGridEmptyNotLoggedInText();
        showMyGrid=false;
     } else {
         if (parseInt(SESSION_INFO.num_open_grids) == 20) {    
  	     setMyGridEmptyLightboxText();
             showMyGrid=false;
         } else {
             showMyGrid=true;
             return;
         }
    }
   } else {
       setMyGridEmptyNotLoggedInText();
       showMyGrid=false;
  }
 

  var maskHeight = $(document).height();
     var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height()+(window.pageYOffset*2);
		var winW = $(window).width();
              
		//Set the popup window to center
		$("#dialogMyGridEmpty").css('top',  winH/2-$("#dialogMyGridEmpty").height()/2);
		$("#dialogMyGridEmpty").css('left', winW/2-$("#dialogMyGridEmpty").width()/2);
	
        $("#dialogMyGridEmpty").fadeIn(400); 
	$("#dialogMyGridEmpty").css('visibility', 'visible');
}
function setCurrentStatusSize(newStatus) {

  var fontSize = 18;

  var lineHeight = 20;

document.getElementById('CurrentStatusDummyDivDetermineHeight').style.fontSize='18px';

      document.getElementById('CurrentStatusDummyDivDetermineHeight').style.lineHeight='20px';

       document.getElementById('CurrentStatusDummyDivDetermineHeight').innerHTML= newStatus; 



maxStatusHeight = 70;

if (isTrends) {

  maxStatusHeight = 63;

}



      while ((document.getElementById('CurrentStatusDummyDivDetermineHeight').clientHeight) > maxStatusHeight) {

           fontSize = fontSize -.2;

           lineHeight = fontSize + .7;  

           document.getElementById('CurrentStatusDummyDivDetermineHeight').style.fontSize=fontSize+'px';

           document.getElementById('CurrentStatusDummyDivDetermineHeight').style.lineHeight=lineHeight+'px';

        

      } 



    $('#myLastTweetSpan').css('font-size',fontSize+'px');

     $('#myLastTweetSpan').css('line-height',lineHeight+'px');



}



function updateStat(statDiv, currentStatVal) {

   if ($(statDiv).html() != currentStatVal) {

        $(statDiv).fadeOut(300, function () { 

             $(statDiv).html(currentStatVal); 

             $(statDiv).fadeIn(300);

        });

   }

}



function updateMyStats() {

    updateStat('#followingStats',SESSION_INFO.followingCount);

    updateStat('#followStats',SESSION_INFO.followersCount);

    updateStat('#listedStats',SESSION_INFO.listedCount);

}



function refreshStats() { 



      $.ajax({

	 type: "POST",

	 url: "/action/refresh_user",

	 data: "",

	 dataType: "json",

	        success: function(newSessionJson) {

                    SESSION_INFO= newSessionJson;

                    setMyCurrentStatus(SESSION_INFO.lastTweet);

	         },

	         error: function(msg) {

		    notifyError('Failed to update stats.');

	         },

	

	});



}



function setMyCurrentStatus(newStatus) { 

   setCurrentStatusSize(newStatus);

    $('#myLastTweetSpan').html(newStatus); 

     $('#myLastTweetSpan').fadeIn(600);

   updateMyStats();

}





function updateStatusAction() {



    var f = function() {

	

	$("#lightboxSubmitButton").unbind("click");

	

	$("#lightboxSubmitButton").bind( "click", function(e) {

		

		txt = $("#dialogPOSTtextfield").val();

		closeLightbox();



		$.ajax({

			type: "POST",

			url: "/action/update_status",

			data: {"textfield": txt},

                        dataType: "json",

			success: function(newSessionJson) {

                            notifySuccess('Status updated!');

                             SESSION_INFO= newSessionJson;

                            setMyCurrentStatus(SESSION_INFO.lastTweet);

                            closeLightbox();

			},

			error: function(msg) {

				notifyError('Status update failed.  Please try again.');

			},

			

		});

		

		return false;

	});

	

       openLightbox();

    }

    

    return f;

}



function replyToAction(tweeterId) {

    

    var f = function() {

	

	$("#lightboxSubmitButton").unbind("click");

	

	$("#lightboxSubmitButton").bind( "click", function(e) {

		

		txt = $("#dialogPOSTtextfield").val();

		curTweet = currentTweet[tweeterId];

		if (isTrends) {

                   screenName =          

                      tweetsJSON.tweeters[tweeterId].tweets[curTweet].screenName;

                } else {

                   screenName = tweetsJSON.tweeters[tweeterId].screenname;

                }

               

		tweetid = tweetsJSON.tweeters[tweeterId].tweets[currentTweet[tweeterId]].id;

		

		data = 'in_reply_to_status_id=' + tweetid + "&textfield=" + escape(txt)

		

		$.ajax({

			type: "POST",

			url: '/action/reply_to',

			data: data,

			 dataType: "json",

			success: function(newSessionJson) {

                             notifySuccess('Reply to @' + screenName + ' sent.');

                              SESSION_INFO= newSessionJson;

                              setMyCurrentStatus(SESSION_INFO.lastTweet);

	                      closeLightbox();

			},

			error: function(msg) {

				notifyError("Your reply to @" + screenName + " failed.  Please try again.");

			},

			

		});

		

		return false;

	});

	

	openLightbox();

    }

    

    return f;

}



function replyToTwitGrids() {

  

    var f = function() {

	

	$("#lightboxSubmitButton").unbind("click");

	

	$("#lightboxSubmitButton").bind( "click", function(e) {

		

		txt = $("#dialogPOSTtextfield").val();

		

		

               

		tweetid = 'twitgrids'

		

		data = 'in_reply_to_status_id=' + tweetid + "&textfield=" + escape(txt)

		

		$.ajax({

			type: "POST",

			url: '/action/reply_to',

			data: data,

			 dataType: "json",

			success: function(newSessionJson) {

                         notifySuccess("Tweet to @twitgrids sent.");

                         SESSION_INFO= newSessionJson;

                         setMyCurrentStatus(SESSION_INFO.lastTweet);

                                closeLightbox();

			},

			error: function(msg) {

				notifyError("Error in sending tweet to @twitgrids.  Please try again.");

			},

			

		});

		

		return false;

	});

	

	openLightbox();

    }

    

    return f;

}





function retweetAction(tweeterId) {

    

     var f = function() {

	

     



	$("#lightboxSubmitButton").unbind("click");

	

	$("#lightboxSubmitButton").bind( "click", function(e) {

		

		txt = $("#dialogPOSTtextfield").val();

	 curTweet = currentTweet[tweeterId];

		if (isTrends) {

                  screenName =  tweetsJSON.tweeters[tweeterId].tweets[curTweet].screenName;

                } else {

                   screenName = tweetsJSON.tweeters[tweeterId].screenname;

                }



		$.ajax({

			type: "POST",

			url: "/action/update_status",

			data: {"textfield":txt},

			 dataType: "json",

			success: function(newSessionJson) {

  notifySuccess('RT @' +  screenName + ' sent.');

                         SESSION_INFO= newSessionJson;

                         setMyCurrentStatus(SESSION_INFO.lastTweet);

                      

                                 closeLightbox();

			},

			error: function(msg) { 

                         notifyError('RT @' +  screenName + ' failed.  Please try again.');

			},

			

		});

		

		return false;

	});

	

	openLightbox();

    }

    

    return f;

}

function followIndividual(screenName) {
  if (typeof(SESSION_INFO) != "undefined") {
     if (SESSION_INFO.have_oauth == 0) {
        displayYouMustSignInLightbox();
        return;
     } 
   } else {
        displayYouMustSignInLightbox();
	return;    
   }

 url = "/action/follow?screen=" + screenName;


  

  $.ajax({

	type: "POST",

	url: url,

	data: "",

	 dataType: "json",

	        success: function(newSessionJson) {

                successMsg = 'You are now following ' + name + ' (@' + screenName + ')';

                notifySuccess(successMsg);

                SESSION_INFO= newSessionJson;

                setMyCurrentStatus(SESSION_INFO.lastTweet);

	},

	error: function(msg) {

		notifyError('Error in following ' + name + ' (@' + screenName + ').  Please try again.');

	},

	

	});

	

  return false;


}

function followAction(tweeterId) {

   if (typeof(SESSION_INFO) != "undefined") {

     if (SESSION_INFO.have_oauth == 0) {

        displayYouMustSignInLightbox();

        return;

     } 

   } else {

        displayYouMustSignInLightbox();

	return;    

   }

  

curTweet = currentTweet[tweeterId];

  if (isTrends) {

     followId =  tweetsJSON.tweeters[tweeterId].tweets[curTweet].id;

     name = tweetsJSON.tweeters[tweeterId].tweets[curTweet].screenName;

     screenName = name;

  } else {

     followId = tweetsJSON.tweeters[tweeterId].userid;

     name = tweetsJSON.tweeters[tweeterId].name;

     screenName = tweetsJSON.tweeters[tweeterId].screenname;

  }



  url = "/action/follow?screen=" + screenName;


  

  $.ajax({

	type: "POST",

	url: url,

	data: "",

	 dataType: "json",

	        success: function(newSessionJson) {

                successMsg = 'You are now following ' + name + ' (@' + screenName + ')';

                notifySuccess(successMsg);

                SESSION_INFO= newSessionJson;

                setMyCurrentStatus(SESSION_INFO.lastTweet);

	},

	error: function(msg) {

		notifyError('Error in following ' + name + ' (@' + screenName + ').  Please try again.');

	},

	

	});

	

  return false;



}



function followTwitGrids() {

   if (typeof(SESSION_INFO) != "undefined") {

     if (SESSION_INFO.have_oauth == 0) {

        displayYouMustSignInLightbox();

        return;

     } 

   } else {

        displayYouMustSignInLightbox();

	return;    

   }

  

  url = "/action/follow?userid=57580303";

  

  $.ajax({

	type: "POST",

	url: url,

        data: "",

	 dataType: "json",

			success: function(newSessionJson) {

                         notifySuccess("You are now following @twitgrids.")

                         SESSION_INFO= newSessionJson;

                        setMyCurrentStatus(SESSION_INFO.lastTweet);

	},

	error: function(msg) {

		notifyError("Error in following @twitgrids. Please try again.");

	},

	

	});

	

  return false;



}





function myGridAction(tweeterId,action,reAddTweet,reAddTweetFontSize,reAddTweetLineHeight) {



 if (typeof(SESSION_INFO) != "undefined") {

     if (SESSION_INFO.have_oauth == 0) {

        displayYouMustSignInLightbox();

        return;

     } 

   } else {

        displayYouMustSignInLightbox();

        return;

   }





  if (action == 'add') {

   if (parseInt(SESSION_INFO.num_open_grids) == 0) {

      notifyError('MyGrid is full.  Remove someone by clicking -My on the MyGrid page.');

   }

  }

  

  url = "/action/mygrid/" + action + "?id=" + tweetsJSON.tweeters[tweeterId].userid;





  

  $.ajax({

	type: "POST",

	url: url,

        data: "",

	success: function(msg) {

       SESSION_INFO= msg;

         if (action =='add') {

            if (typeof(reAddTweet) != "undefined") {

              $('#grid' +tweeterId+ '-tweet').html(reAddTweet);

              $('#grid' +tweeterId+ '-tweet').css('font-size',reAddTweetFontSize);

               $('#grid' +tweeterId+ '-tweet').css('line-height',reAddTweetLineHeight);

               $('#grid' +tweeterId+ '-mygrid').css('display','block');

               $('#grid' +tweeterId+ '-follow').css('display','inline');

               $('#container #grid' +tweeterId+ '-time').css('display','block');

            

             }

            

successMsg = 'Added ' + tweetsJSON.tweeters[tweeterId].name + ' (@' + tweetsJSON.tweeters[tweeterId].screenname+ ') to MyGrid';

notifySuccess(successMsg);

         }





         if (action == 'remove') {

               readdID = 'grid' +tweeterId+ '-readd';

               readdMe = "<br><A ID=\"" + readdID + "\" HREF=\"\" >Add back to MyGrid</A>";

		reAddTweet = $('#grid' +tweeterId+ '-tweet').html();

                reAddTweetFontSize = $('#grid' +tweeterId+ '-tweet').css('font-size');

                reAddTweetLineHeight = $('#grid' +tweeterId+ '-tweet').css('line-height');

               $('#grid' +tweeterId+ '-tweet').html(readdMe);

               $('#grid' +tweeterId+ '-tweet').css('font-size','21.5px');

               $('#grid' +tweeterId+ '-tweet').css('line-height','23px');

               $('#'+readdID).click( function(event) {

myGridAction(tweeterId,'add',reAddTweet,reAddTweetFontSize,reAddTweetLineHeight); return false; }  );

               $('#grid' +tweeterId+ '-mygrid').css('display','none');

               $('#grid' +tweeterId+ '-follow').css('display','none');

               $('#container #grid' +tweeterId+ '-time').css('display','none');

           }





    

	},

	error: function(msg) {

               var preposition = 'to';

               var actionErrMsg = 'adding';

               if (action == 'remove') {

                  preposition = 'from';

                  actionErrMsg = 'removing';

               }

		notifyError('Error in ' + actionErrMsg  + ' ' + tweetsJSON.tweeters[tweeterId].name + ' (' + tweetsJSON.tweeters[tweeterId].screenname  + ') ' + preposition + ' MyGrid.');

	},

	

	});

	

  return false;

}



// KM END



function getObject(obj) {

  var theObj;

  if(document.all) {

    if(typeof obj=="string") {

      return document.all(obj);

    } else {

      return obj.style;

    }

  }

  if(document.getElementById) {

    if(typeof obj=="string") {

      return document.getElementById(obj);

    } else {

      return obj.style;

    }

  }

  return null;

}



function showInfo(id) {





  thisTweeter = tweetsJSON.tweeters[id];









$("#tweetStatsImage").html('<IMG SRC="' + thisTweeter.profile_image_url.replace( /(^.*)_normal\.(\w\w\w\w?)$/, "$1_bigger.$2")

 + '"  target=_blank></>');





  $("#tweetStatsName").html(tweetsJSON.tweeters[id].name);

  $("#tweetStatsScreenname").html("<a TARGET=_NEW href=\"http://www.twitter.com/" +  tweetsJSON.tweeters[id].screenname + "\">@" + tweetsJSON.tweeters[id].screenname+ "</a>");

 if (thisTweeter.verified == true) {

      $("#tweetStatsVerified").html('Verified');

  } else {

      $("#tweetStatsVerified").html('not verified');

   }

  $("#tweetStatsDescription").html(thisTweeter.description);

  $("#tweetStatsFollowers").html(thisTweeter.followers_count);

  $("#tweetStatsFollowing").html(thisTweeter.friends_count);

  $("#tweetStatsRank").html('4'); 

  $("#tweetStatsUrl").html('<A HREF="' + thisTweeter.url + '"  target=_blank>' + thisTweeter.url + '</a>');



}



function initReply(type,textfield, id, exit,text,characters, action) {

   hideLightBox();

   closeLightbox();

   if (typeof(SESSION_INFO) != "undefined") { 

     if (SESSION_INFO.have_oauth == 0) {

          closeLightbox(); // do not show lightbox with form 

          displayYouMustSignInLightbox(); 

          return;

     } else {

         $('#basic').css('display','inline');

     }  

   } else {

          closeLightbox(); // do not show lightbox with form 

          displayYouMustSignInLightbox();

          return;

   }



  var textfieldObj = getObject('dialogPOSTtextfield');



// KM BEGIN

  action_url = action();

 

// KM END



 if (type == '@TwitGrids') {

     document.getElementById('tweetNameLightbox').firstChild.nodeValue = 'Reply to @TwitGrids';

      textfieldObj.value = "@TwitGrids" + ' ';

 }


 curTweet = currentTweet[id];

 if (type == '@') {

      

      if (isTrends) {

         atName =tweetsJSON.tweeters[id].tweets[curTweet].screenName;

      } else {

         atName =  tweetsJSON.tweeters[id].name;

      }



      if (isTrends) {

        screenName = tweetsJSON.tweeters[id].tweets[curTweet].screenName;

      } else {

         screenName = tweetsJSON.tweeters[id].screenname;

      }

  

     document.getElementById('tweetNameLightbox').firstChild.nodeValue = 'Reply to ' + atName;

      textfieldObj.value = "@" + screenName + ' ';

 }



if (type == 'RT') {



      if (isTrends) {

         atName = tweetsJSON.tweeters[id].tweets[curTweet].screenName;

      } else {

         atName =  tweetsJSON.tweeters[id].name;

      }



  if (isTrends) {

   rtName = tweetsJSON.tweeters[id].tweets[curTweet].screenName;

  } else {

   rtName  = tweetsJSON.tweeters[id].screenname;

  }



 document.getElementById('tweetNameLightbox').firstChild.nodeValue = 'Retweet ' + atName;



  x= "RT @" + rtName + " " + tweetsJSON.tweeters[id].tweets[currentTweet[id]].tweet;





 textfieldObj.value = x;

}



 if (type == 'UpdateStatus') {

  document.getElementById('tweetNameLightbox').firstChild.nodeValue = 'What are you doing?';

 textfieldObj.value ='';

}



  var length=characters - textfieldObj.value.length;

  submitButtonDisableCheck(length);

  var exitObj=getObject(exit);

  exitObj.innerHTML = text.replace("{CHAR}",length);

}



function clearReply(textfield) {

   var textfieldObj = getObject(textfield);

   if (textfieldObj != null) {

      textfieldObj.value = " ";

   }

}



function submitButtonDisableCheck(charsLeft) {

  if ((charsLeft < 0) || (charsLeft==140)) {

      $('#lightboxSubmitButton').attr("disabled", "disabled");

  } else {

       $('#lightboxSubmitButton').removeAttr("disabled");

  }

}



function toCount(entrance,exit,text,characters) {

  var entranceObj=getObject(entrance);

  var exitObj=getObject(exit);

  var length=characters - entranceObj.value.length;

 

  if(length <= 0) { 

    text='<span class="disable"> '+text+' </span>';

  } 



  submitButtonDisableCheck(length);

  exitObj.innerHTML = text.replace("{CHAR}",length);

}





function showAdvertise() {

   hideLightBox();

}



function hideLightBox() {

   $('#mask').hide();

   $('.window').hide();



}



function showIE6Lightbox(div) {



	var maskHeight = $(document).height();

	var maskWidth = $(window).width();

	

	//Set heigth and width to mask to fill up the whole screen

	$('#mask').css({'width':maskWidth,'height':maskHeight});

		

	//transition effect		

	$('#mask').fadeIn(1000);	

	$('#mask').fadeTo("slow",0.8);	

	

	//Get the window height and width

	var winH = $(window).height()+(window.pageYOffset*2);

	var winW = $(window).width();

              

	//Set the popup window to center

	$(div).css('top',  winH/2-$(div).height()/2);

	$(div).css('left', winW/2-$(div).width()/2);



        $(div).fadeIn(400); 

	$(div).css('visibility', 'visible');

}



function showDialog(div) {



	var maskHeight = $(document).height();

	var maskWidth = $(window).width();

	

	//Set heigth and width to mask to fill up the whole screen

	$('#mask').css({'width':maskWidth,'height':maskHeight});

		

	//transition effect		

	$('#mask').fadeIn(1000);	

	$('#mask').fadeTo("slow",0.8);	

	

	//Get the window height and width

	var winH = $(window).height()+(window.pageYOffset*2);

	var winW = $(window).width();

              

	//Set the popup window to center

	$(div).css('top',  winH/2-$(div).height()/2);

	$(div).css('left', winW/2-$("#dialogContactUs").width()/2);



        $(div).fadeIn(400); 

	$(div).css('visibility', 'visible');



}



function setStatsValFontSize(stat, div) {

  if ((SESSION_INFO.followersCount.length >= 9) ||

      (SESSION_INFO.followingCount.length >= 9) ||

      (SESSION_INFO.listedCount.length >= 9)) {

          $('#followStats').css('font-size','8.8px');

          $('#followingStats').css('font-size','8.8px');

          $('#listedStats').css('font-size','8.8px');

  } else if ((SESSION_INFO.followersCount.length >= 7) ||

      (SESSION_INFO.followingCount.length >= 7) ||

      (SESSION_INFO.listedCount.length >= 7)) {

         $('#followStats').css('font-size','10.8px');

          $('#followingStats').css('font-size','10.8px');

          $('#listedStats').css('font-size','10.8px');

  }else {

          $('#followStats').css('font-size','13x');

          $('#followingStats').css('font-size','13px');

          $('#listedStats').css('font-size','13px');

  }



  if (SESSION_INFO.screen_name.length >= 14) {

        $('#signedInId').css('font-size','11.2px');

  } else if (SESSION_INFO.screen_name.length >= 12) {

          $('#signedInId').css('font-size','14.5px');

  } else if (SESSION_INFO.screen_name.length >= 10) {

        $('#signedInId').css('font-size','15px');

  } else {

       $('#signedInId').css('font-size','17px');

  } 



}



// KM BEGIN





function loginOrLogoutAction(elementDiv) {

   if (typeof(SESSION_INFO) != "undefined") {

     if (SESSION_INFO.have_oauth == 1) {

       $('#signinImg').css('display','none');

       $('#signoff').css('display','block');



       $('#signedInUserIconImg').attr('src',SESSION_INFO.icon);

         setStatsValFontSize();

       $('#signedInId').html(SESSION_INFO.screen_name);

       $('#followingStats').html(SESSION_INFO.followingCount);

       $('#followStats').html(SESSION_INFO.followersCount); 

        $('#listedStats').html(SESSION_INFO.listedCount); 

       setMyCurrentStatus(SESSION_INFO.lastTweet);

       $('#myLastTweetSpan').html(SESSION_INFO.lastTweet); 

       $('#updateStatusSignedOut').css('display','none');

     

     } else {

       $('#signinImg').css('display','block');

       $('#signoffControls').css('display','none');

       $('#statsLabels').css('display','none');

       $('#signedInUserIconImg').css('display','none');   

       $('#signedInId').css('display','none');    

       $('#updateStatusSignedIn').css('display','none');

 $('#myLastTweet').css('display','none');

     }

   } else {

       $('#signinImg').css('display','block');

       $('#signoffControls').css('display','none');

       $('#statsLabels').css('display','none');

       $('#signedInUserIconImg').css('display','none'); 

       $('#signedInId').css('display','none');  

       $('#updateStatusSignedIn').css('display','none');

       $('#myLastTweet').css('display','none');

   }

}



  var otherTips=new Array();

       	otherTips[0] = "Follow and discover celebrities on Twitter!";

       	otherTips[1] = "2,970 tweeters and current trends on 89 grids!";

	otherTips[2] = "<B>Easy Scroll!</b>  Scroll through tweets using your mouse scroll wheel!";

	otherTips[3] = "MyGrid is your custom built grid.  Use +My button to add tweeters!";

        otherTips[4] = "Trending topics tweets are spam filtered!";

	otherTips[5] = "<A HREF='#dialogPOST' name='modal' onclick=\"initReply('@TwitGrids','textfield',0,'sBann','{CHAR}',140,replyToTwitGrids());\">@TwitGrids</A> to recommend a twitter user.";

	otherTips[6] =  "<A HREF=\"/action/twitter_sign_in\">Sign in</a> with Twitter to update your status via TwitGrids!"; 

	otherTips[7] =  "<A HREF=\"/action/twitter_sign_in\">Sign in</a> with Twitter to @ reply anyone on a TwitGrid!";

	otherTips[8] =  "<A HREF=\"/action/twitter_sign_in\">Sign in</a> with Twitter and create your own grid!";



function setTip() {

 if (typeof(SESSION_INFO) != "undefined") {
     if (SESSION_INFO.have_oauth == 0) {
	rotateToIndex = 8;
         $('#tipsMainTip').html(otherTips[Math.floor(Math.random()*9)]);
     } else {
	rotateToIndex = 5;
        $('#tipsMainTip').html(otherTips[Math.floor(Math.random()*5)]);
     }

   } else {

       rotateToIndex = 8;

   }

   $('#tipsMainTip').html(otherTips[0]);
   rotateTips(1,rotateToIndex);    
  

}


$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
}

function rotateTips(i, rotateToIndex) {

 $('#tipsMainTip').delay(6000).fadeOut(200, function () { 
           $('#tipsMainTip').html(otherTips[i]); 
            $('#tipsMainTip').fadeIn(200);
            i = i + 1;
            if (i < rotateToIndex) {
	    	 rotateTips(i,rotateToIndex);
             } else {
                $('#tipsMainTip').html(otherTips[0]); 
                $('#tipsMainTip').fadeIn(1000);
             }
            
 });

/*
   $('#tipsMainTip').delay(6000).fadeOut(200, function () { 
           

             $('#tipsMainTip').html(otherTips[i]); 
             $('#tipsMainTip').fadeIn(200);
            
             i++;
             if (i < rotateToIndex) {
	    	 rotateTips(i,rotateToIndex);
             } else {
                $('#tipsMainTip').html(otherTips[0]); 
                $('#tipsMainTip').fadeIn(1000);
             }
        },5000);
*/

}


function notifyError(msg) {

$('#notification').bar({

color:'#fff',background_color : '#AA2222',removebutton: true,time: 3200,message:msg

});

}



function notifySuccess(msg) {

$('#notification').bar({

color:'#000',background_color : '#FFFFFF',removebutton: true,time: 2200,message:msg

});

}

function myGridClicked() {
	displayMyGridEmptyLightboxIfNecessary();
        if (showMyGrid) {
          location.href='/twitter/myGrid-twitter.html';
        }
}



//////

///  notification

//////

(function($) {

	

	$.fn.bar = function(options) {

		var opts = $.extend({}, $.fn.bar.defaults, options);

		return this.each(function() {

			$this = $(this);

			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			

			

				if(!$('.jbar').length){

					timeout = setTimeout('$.fn.bar.removebar()',o.time);

					var _message_span = $(document.createElement('span')).addClass('jbar-content').html(o.message);

					_message_span.css({"color" : o.color});

					var _wrap_bar;

					(o.position == 'bottom') ? 

					_wrap_bar	  = $(document.createElement('div')).addClass('jbar jbar-bottom'):

					_wrap_bar	  = $(document.createElement('div')).addClass('jbar jbar-top') ;

					

					_wrap_bar.css({"background-color" 	: o.background_color});

					if(o.removebutton){

						var _remove_cross = $(document.createElement('a')).addClass('jbar-cross');

						_remove_cross.click(function(e){$.fn.bar.removebar();})

					}

					else{				

						_wrap_bar.css({"cursor"	: "pointer"});

						_wrap_bar.click(function(e){$.fn.bar.removebar();})

					}	

						

					_wrap_bar.append(_message_span).append(_remove_cross).fadeIn('fast').insertAfter($('BODY'));

				}

			

			

			

		});

	};

	var timeout;

	$.fn.bar.removebar 	= function(txt) {

		if($('.jbar').length){

			clearTimeout(timeout);

			$('.jbar').fadeOut('fast',function(){

				$(this).remove();

			});

		}	

	};

	$.fn.bar.defaults = {

		background_color 	: '#FFFFFF',

		color 				: '#000',

		position		 	: 'top',

		removebutton     	: true,

		time			 	: 5000	

	};

	

})(jQuery);

//// notification end


//parse url
jQuery.url = function()
{
	var segments = {};
	
	var parsed = {};
	
	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {
	
		url : window.location, // default URI is the page in which the script is running
		
		strictMode: false, // 'loose' parsing by default
	
		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
		
		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},
		
		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, // more intuitive, fails on relative paths and deviates from specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ //less intuitive, more accurate to the specs
		}
		
	};
	
    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */		
	var parseUri = function()
	{
		str = decodeURI( options.url );
		
		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 * 
	 * @param string key The key whose value is required
     */		
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		} 
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}
	
		return ( parsed[key] === "" ) ? null : parsed[key];
	};
	
	/**
     * Returns the value of the required query string parameter.
  	 * 
	 * @param string item The parameter whose value is required
     */		
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...	
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
     */	
	var setUp = function()
	{
		parsed = parseUri();
		
		getSegments();	
	};
	
    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};
	
	return {
		
	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},
		
		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */		
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},		
		
		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */	
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...	
			} 
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},
		
		attr : key, // provides public access to private 'key' function - see above
		
		param : param // provides public access to private 'param' function - see above
		
	};
	
}();


/* ----------------------------------------------------------- */
function initIndividualReply(type,textfield, name, screenName, exit,text,characters, action) {

   hideLightBox();

   closeLightbox();

   if (typeof(SESSION_INFO) != "undefined") { 

     if (SESSION_INFO.have_oauth == 0) {

          closeLightbox(); // do not show lightbox with form 

          displayYouMustSignInLightbox(); 

          return;

     } else {

         $('#basic').css('display','inline');

     }  

   } else {

          closeLightbox(); // do not show lightbox with form 

          displayYouMustSignInLightbox();

          return;

   }



  var textfieldObj = getObject('dialogPOSTtextfield');

  action_url = action();

   
    document.getElementById('tweetNameLightbox').firstChild.nodeValue = 'Reply to ' + atName;

      textfieldObj.value = "@" + screenName + ' ';

  var length=characters - textfieldObj.value.length;
  submitButtonDisableCheck(length);
  var exitObj=getObject(exit);
  exitObj.innerHTML = text.replace("{CHAR}",length);

}

function replyToIndividual(screenName) {

    

    var f = function() {


	$("#lightboxSubmitButton").unbind("click");	

	$("#lightboxSubmitButton").bind( "click", function(e) {		

		txt = $("#dialogPOSTtextfield").val();              
		

		data = "textfield=" + escape(txt);
		
		$.ajax({

			type: "POST",

			url: '/action/reply_to',

			data: data,

			 dataType: "json",

			success: function(newSessionJson) {

                             notifySuccess('Reply to @' + screenName + ' sent.');

                              SESSION_INFO= newSessionJson;

	                      closeLightbox();

			},

			error: function(msg) {

				notifyError("Your reply to @" + screenName + " failed.  Please try again.");

			},

			

		});

		

		return false;

	});

	

	openLightbox();

    }

    

    return f;

}


function addIndividualToMyGrid(tweeterId, name) {



 if (typeof(SESSION_INFO) != "undefined") {

     if (SESSION_INFO.have_oauth == 0) {

        displayYouMustSignInLightbox();

        return;

     } 

   } else {

        displayYouMustSignInLightbox();

        return;

   }

   if (parseInt(SESSION_INFO.num_open_grids) == 0) {

      notifyError('MyGrid is full.  Remove someone by clicking -My on the MyGrid page.');

   }


  url = "/action/mygrid/add" + "?id=" + tweeterId;


  $.ajax({

	type: "POST",

	url: url,

        data: "",

	success: function(msg) {

          SESSION_INFO= msg;
            
          successMsg = 'Successfully added ' + name + ' to MyGrid';

          notifySuccess(successMsg);
	},

	error: function(msg) {

               var preposition = 'to';

               var actionErrMsg = 'adding';

		notifyError('Error in adding ' + name + ' to MyGrid');

	},

	

	});

	

  return false;

}

