(function($){ 
	$.fn.extend({  
		visible: function() {return $(this).css({visibility:"visible"});},
		invisible: function() {return $(this).css({visibility:"hidden"});},
		attr_reset: function(attr_name) {return $(this).attr(attr_name, $(this).attr(attr_name)); },
		to_parent_width: function() {
			var t = $(this);
			var parent = t.parent();
			var pw = parent.width();
			t.css("width",pw);
			t.css("width",2*t.width()-t.outerWidth()).visible();
			return t;
		}
	}); 
})(jQuery);

String.whiteSpace = [];
String.whiteSpace[0x0009] = true;
String.whiteSpace[0x000a] = true;
String.whiteSpace[0x000b] = true;
String.whiteSpace[0x000c] = true;
String.whiteSpace[0x000d] = true;
String.whiteSpace[0x0020] = true;
String.whiteSpace[0x0085] = true;
String.whiteSpace[0x00a0] = true;
String.whiteSpace[0x1680] = true;
String.whiteSpace[0x180e] = true;
String.whiteSpace[0x2000] = true;
String.whiteSpace[0x2001] = true;
String.whiteSpace[0x2002] = true;
String.whiteSpace[0x2003] = true;
String.whiteSpace[0x2004] = true;
String.whiteSpace[0x2005] = true;
String.whiteSpace[0x2006] = true;
String.whiteSpace[0x2007] = true;
String.whiteSpace[0x2008] = true;
String.whiteSpace[0x2009] = true;
String.whiteSpace[0x200a] = true;
String.whiteSpace[0x200b] = true;
String.whiteSpace[0x2028] = true;
String.whiteSpace[0x2029] = true;
String.whiteSpace[0x202f] = true;
String.whiteSpace[0x205f] = true;
String.whiteSpace[0x3000] = true;
/**
 Trims leading and trailing whitespace from a string.
 http://yesudeep.wordpress.com/2009/07/31/even-faster-string-prototype-trim-implementation-in-javascript/
 @returns the trimmed string.
*/

function trim17(str){
    var len = str.length;
    if (len){
        var whiteSpace = String.whiteSpace, i = 0;
        while (whiteSpace[str.charCodeAt(--len)]);
        if (++len){
            while (whiteSpace[str.charCodeAt(i)]){ ++i; }
        }
        str = str.substring(i, len);
    }
    return str;
}
/**
 Trims leading and trailing whitespace from a string.
 @returns the trimmed string.
*/
String.prototype.trim = function() {
  return trim17(this);
};

/**
 Checks if the string starts with the specified sub string.

 @param str the sub string to check for.
 @returns true if the string starts with the sub string, otherwise
  false.
*/

String.prototype.startsWith = function(str) {
  return this.indexOf(str) === 0;
};

/**
 Checks if the string ends with the specified sub string.

 @param str the sub string to check for.
 @returns true if the string ends with the sub string, otherwise
  false.
*/

String.prototype.endsWith = function(str) {
  var offset = this.length - str.length;
  return offset >= 0 && this.lastIndexOf(str) === offset;
};

Array.prototype.max = function() {
    return Math.max.apply(null, this);
};
Array.prototype.min = function() {
    return Math.min.apply(null, this);
};

CheddrUtil = new function() {
  this.globals = {
   waitForThen: function (things, what) {
      for (i=0;i<=things.length;i++) {
        if (typeof eval(things[i]) != 'undefined'){
        } else { setTimeout('waitForLoadThen("'+ what.toString()+'")', 100); return false; }
      }
      return eval(what);
    },
    getSearch: function(){
      $.jsonp({
        url: "http://search.twitter.com/search.json?q=" + encodeURIComponent($cheddr['page_data']['filter']['query']),
        callbackParameter: "callback",
        success: function(json) {
          // This will be called in case of success no matter the callback name
       },
        error: function() {
          // This will be called in case of error no matter the callback name
        }
      });
    },
    startPeriodicUpdate: function(){
      return true;
      $.PeriodicalUpdater('/streams/company-only/count/' + $cheddr['page_data']['entries']['last_id'] + '.json', {
        method: 'get',          // method; get or post
        data: '',               // array of values to be passed to the page - e.g. {name: "John", greeting: "hello"}
        minTimeout: 1000,       // starting value for the timeout in milliseconds
        maxTimeout: 30000,      // maximum length of time between requests
        multiplier: 2,          // if set to 2, timerInterval will double each time the response hasn't changed (up to maxTimeout)
        type: 'json'            // response type - text, xml, json, etc.  See $.ajax config options
      }, function(data) {
        if ((data) && data['entries'] && data['entries']['count']) {
          var c_entries_count = $('span#c_entries_count');
          $('span#entries_count', c_entries_count).html(data['entries']['count']);
          c_entries_count.show();
        } else {
        }
      });
    },
    getUpdates: function(){
      waitForThen(["$cheddr['page_data']['entries']","$cheddr['page_data']['entries']['last_id']"], "CheddrUtil.startPeriodicUpdate();");
    }
  };
  this.init = function() {
    // Define an object in the global scope (i.e. the window object)
    window.$cheddr_utils = {};
    window.$cheddr_utils = $.extend(CheddrUtil.globals, window.$cheddr_utils);
    CheddrUtil = $.extend(CheddrUtil.globals, CheddrUtil);
  };
}

var tt;
if (!tt){tt = {};}
tt.string = {
	voteBefore:"Like?",voteAfter:"Liked!",
	reportBefore:"Report",reportAfter:"Reported",
	retweet:"<b class='i16 retweet'>&nbsp;</b><span class='text'>reTweet</span>",
	ajaxError:"There has been a network issue when accessing the information you requested. Please try again later.",
	ajaxShownAll:"All the entries have been shown in this category",
	delete_confirm_primary_message:"Are you sure you want to delete this entry?",
	delete_confirm_secondary_message:"This can't be undone...",
	blacklist_confirm_primary_message:"Are you sure you want to blacklist this user?",
	blacklist_confirm_secondary_message:"This user will no longer be able to post to this site...",
	twitpic_image_move:"The image location for this entry has been moved. Trying to fetch the latest image from the remote server ",
	fail_to_retrieve_image:"We are unable to retrieve the image for this entry. Please try again in a few minutes..."
};
tt.icons = {
	loading:'<b class="i00 ajax_load">&nbsp;</b>'
}
tt.config = {
	textarea_chars_limit:120,
	ajax_options:{
		dataType:"json",
		timeout:10000,
		error:function(){
			alert(tt.string.ajaxError);
		}
	},
	entry_image_size_restriction:{
		width:160,
		height:140
	}
};


tt.connects = {
	facebook:function(){
		u=location.href;
		t=document.title;
		window.open('http://www.facebook.com/sharer.php?u='+
			encodeURIComponent(u)+'&t='+
			encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;
	}
}


function setCurrentUser() {
  console.log('enter setCurrentUser()');
}

(function(){
	if (!tt.init){tt.init = {};}
	var S = S || tt.string;
  var C = C || tt.config;
	var U = false;
  if (Cheddr.is_logged_in() == true) {
    console.log('~~~ logged_in == true, setting tt.current_user and U');
    U = tt.current_user = {
      avatar:         $cheddr['page_data']['participant']['avatar_path'],
      screen_name:    $cheddr['page_data']['participant']['screen_name'],
      entry_id :      null
    }
  }
  else {
    console.log('~~~ logged_in == false!');
  }

//********** init functions ***********//

	//tweet box initialization function.  TODO:  document what this 'initialization' consists of
	tt.init.a_tweet_box = function(tweet_box){
		
		if (tweet_box.length==0)
		{
			return;
		}
				
		set_up_textarea_limit({target:tweet_box,commonParent:".a_tb",limit:C.textarea_chars_limit});
		
		var send = tweet_box.find("input.submit");
    var the_form = $cheddr['entryForm'];
    $cheddr.entryForm.attr('action', replaceEndPath(location.pathname, 'authorize.html'));
    var the_textarea = the_form.find('textarea');
    the_textarea.attr('value',$cheddr['page_data']['filter']['tweet_box_text'] + ' ');
		send.click(function(){
				ajax_screen({target:tweet_box});
	    	var flag = tweet_box.data("inlineMode") || false; //true => adding comment
				var data = U;
        // ajax entry submit

				function render()
				{
		      function comment_pre_insert(content_stream) {
		      }
		      function tweet_box_pre_insert(content_stream) {
		        content_stream.addClass('highlight');
		      }
					function tweet_box_post_insert(content_stream) {
						tweet_box.data("off")();
						var to = setTimeout(fadeOut, 3000);
						function fadeOut()
						{
							content_stream.find(">.sm_2_a").animate({
								backgroundColor:"#fff",
								borderBottomColor:"#fff",
								borderTopColor:"#fff",
								borderLeftColor:"#fff",
								borderRightColor:"#fff"
							},3000);
							content_stream.removeClass("highlight");
						}
					}
					
					function comment_post_insert(content_stream)
					{
						var parent = content_stream.parents(".a_content-stream");
						parent.find("*").unbind();
						tt.init.a_content_stream(parent);
						parent.data("retweeting",false);
						parent.data("replying",false);
					}
					
		      // determine whether the tweetbox is in an entry or it's the main tweet box
					var insert_target = "";
		      var insert_type=flag?"append":"prepend";
		      var on_pre_insert=flag?comment_pre_insert:tweet_box_pre_insert;
					var on_post_insert=flag?comment_post_insert:tweet_box_post_insert;
					var template_id=flag?"t_comment":"t_content-stream";
					
		      if (flag) { //commenting
						var parent = tweet_box.parents(".p_cs");
						data.id = data.entry_id;
						data.twitter_user_screen_name = U.screen_name;
		        tweet_box.parents(".a_itb").remove();
						parent.find(".replytag").data("replying",false);
						
		        if (parent.find(".a_inline-comments").length == 0) {
							insert_target = $("<div class='a_inline-comments'></div>"); 
		          parent.append(insert_target);
		        }
		        else {
		          insert_target = parent.find(".a_inline-comments");
		        }
		
		      }
					else
					{
						insert_target = $("#p_content_streams");
					}
		
		      populate({
		        data:data,
		        insert_type:insert_type,
		        insert_target:insert_target,
		        template_id:template_id,
		        initialization_function:tt.init.a_content_stream,
		        on_pre_insert:on_pre_insert,
						on_post_insert:on_post_insert
		      });
				}

        function submitMessage(){
          the_form = tweet_box.find('form');
					if (flag) //inline comments only
					{
	          var entry_id = tweet_box.parent().parent().find('div.twitter-user').attr('entry_id');
						var screen_name = tweet_box.parent().parent().find('div.twitter-user a:first-child').html();
	          if (entry_id) {
	            var hidden = $('<input type="hidden">');
	            hidden.attr('name','entry[in_reply_to]');
	            hidden.attr('value',entry_id);
	            the_form.append(hidden);
	          }
					}
          // Perform ajax
          if ((!U) || (Cheddr.is_logged_in() == false)) {
            // Perform ajax
            $.post(replaceEndPath(location.pathname, 'authorize.html'), the_form.serialize(), function(return_data){
            });
          } else {
            var options ={
              url:replaceEndPath(location.pathname, 'enter.json'),
              type:"POST",
              data:the_form.serialize(),
              dataType:"json",
              success:function(return_data){
                data.body = return_data.body;
                data.entry_id = return_data.id;
                data.created_at = return_data.created_at;
								data.tweet_id = return_data.tweet_id;
                data.ready = true;
                render();
              }
            };
            $.ajax(options);
          }
        }

        if ((!U) || (Cheddr.is_logged_in() == false)) {
          console.log('no current user, normal form post to oauth!');
          return true;
        } else {
          submitMessage();
					return false; //stop default actions
				}
				return false;
		});
	}

	/*
	purpose: initialize the retweet box. it is called when the user clicks on the reTweet button on the entry
	param: the tweetbox template (t_tweet-box)
	return: nothing
	*/
	tt.init.a_retweet_box = function(tweet_box){
		set_up_textarea_limit({target:tweet_box,commonParent:".a_tb",limit:C.textarea_chars_limit});
		var send = tweet_box.find("input.submit");
    var matches = tweet_box.html().match(/@([a-zA-Z0-9_-]+)/);
    var retweet_screen_name = matches[1];
    send.click(function(){
			ajax_screen({target:tweet_box});
      //Do the retweet logics here
      try {

        var entry_id = tweet_box.parent().parent().find('div.twitter-user').attr('entry_id');
        var the_form = tweet_box.find('form');
        var hidden = $('<input type="hidden">');
        hidden.attr('name','entry[retweet_screen_name]');
        hidden.attr('value',retweet_screen_name);
        the_form.append(hidden);
        hidden = $('<input type="hidden">');
        hidden.attr('name','entry[retweet_entry_id]');
        hidden.attr('value',entry_id);
        the_form.append(hidden);
      } catch (bullshit) {
        alert(bullshit);
      }

      // Perform ajax
      if (Cheddr.is_logged_in()) {
        $.post(replaceEndPath(location.pathname, 'retweet.json'), the_form.serialize(), function(return_data){
          retweetSuccess();
        });
      } else {
        the_form.attr('action', replaceEndPath(location.pathname, 'authorize.html'));
        hidden = $('<input type="hidden">');
        hidden.attr('name','is_retweet');
        hidden.attr('value',true);
        the_form.append(hidden);
        return true;
      }
			
			function retweetSuccess()
			{
				tweet_box.find(".charsLeft").remove();
				tweet_box.find("form").remove();
				tweet_box.data("off")();
				message = "<div>" + S.retweet + " sent...</div>";
				tweet_box.find(".p_tb").append(message);
				var to = setTimeout(hide,3000);
				function hide(){tweet_box.fadeOut();}
			}
			
			return false; //avoid form submit
		});
	}
  
  tt.init.c_lia = function(){
    if (Cheddr.is_logged_in()) {
      $('.login-required').hide();
      var data = {
        screen_name:$cheddr['page_data']['participant']['screen_name'],
        avatar:$cheddr['page_data']['participant']['avatar_path']
      };
      populate({
        data:data,
        insert_type:"append",
        insert_target:$('#c_lia'),
        initialization_function:function(){
          $('.logged-in','#c_lia').show();
        },
        on_pre_insert:function(){
          $('.logged-in','#c_lia').show();
        },
        template_id:"c_logged-in"
      });
      $('.logged-in','#c_lia').show();
    }
    else {
      $('.login-required').show();
    }
  }
  
	tt.init.a_content_streams = function(){
		var cs = $(".a_content-stream");
		cs.each(function(){
			tt.init.a_content_stream($(this));	
		});
	};
  
	tt.init.a_content_stream = function(content_stream){
		var t = content_stream;
		
		var image = t.find(".c_entry-image img");
		var p_cs = t.find(".p_cs");
		var entry_id = t.find(".vcard").attr("entry_id");
		var admin_actions = t.find(".a_admin-actions");
		
		//action links
		var reply = t.find(".reply a");
		var retweet = t.find(".retweet a");
		var vote = t.find(".vote a[class!=liked]");
			// regular user actions
			var report = t.find(".c_reportLink");

			//admin user actions
			var del = admin_actions.find(".delete a");
			var blacklist = admin_actions.find(".blacklist a");

			del.click(function(){
				var confirm_action_options = {
					target: $("body"),
					primary_message: S.delete_confirm_primary_message,
					secondary_message: S.delete_confirm_secondary_message,
					yes:do_it
				};
				
				confirm_action(confirm_action_options);
				
				function do_it()
				{
					var ajax_options = C.ajax_options;
					ajax_options.url = "/entries/delete/" + entry_id + ".json";
					ajax_options.success = function(data){
						if (data.success)
						{
							alert("the entry has been deleted!");
							t.remove();
						}
					};
					$.ajax(ajax_options);
				}
			});

			blacklist.click(function(){
				var confirm_action_options = {
					target: $("body"),
					primary_message: S.blacklist_confirm_primary_message,
					secondary_message: S.blacklist_confirm_secondary_message,
					yes:do_it
				};
				
				confirm_action(confirm_action_options);

				function do_it()
				{
					var ajax_options = C.ajax_options;
					ajax_options.url = "/entries/blacklist/" + entry_id + ".json";
					ajax_options.success = function(data){
						if (data.success)
						{
							alert("the entry has been blacklisted!");
						}
					};
					$.ajax(ajax_options);
				}
			});


			//regular user actions
			var report = t.find(".c_reportLink");
		
		var comments = t.find(".a_inline-comments>div.a_comment");
		var number_of_comments = comments.length;
		var user = {
			screenName:t.find(".screen-name").html()
		};
				


		if(image.length != 0)
		{
			var image_parent = image.parents(".c_entry-image");
			
			function adjust_image(){
				var loading_text = image.siblings(".loading");
				var alert_text = image.siblings(".alert");
				var w = image.width();
				var h = image.height();
				var ratio = w/h;
				var cs_w = t.width();
				var restriction = C.entry_image_size_restriction;

				var w_d = w - restriction.width;
				var h_d = h - restriction.height;

				var small = {};

				var large = {
					width:image.parent().width() - 8,
					height:(image.parent().width() - 8)*(1/ratio)
				};

				if (w_d > 0)
				{
					if (h_d > 0)
					{
						if (w_d > h_d)
						{
							 width_base_adjust();
						}
						else
						{
							height_base_adjust();
						}
					}
					else
					{
						width_base_adjust();
					}
				}
				else //w_d < 0
				{
					if (h_d > 0)
					{
						height_base_adjust();
					}
					else
					{
						small.width = w;
						small.height = h;
					}
				}

				function height_base_adjust()
				{
					small.height = restriction.height;
					small.width = restriction.height*(ratio);
				}
				
				function width_base_adjust()
				{
					small.width = restriction.width;
					small.height = restriction.width*(1/ratio);												
				}

				//instant show
				image.css(small);
				image.css({
					position:"static",
					cursor:"pointer"
				});
				loading_text.remove();
				alert_text.remove();
				image.visible();
				
				if (!image.data("click_attached"))
				{
					image.click(function(){
						if (!image.data("enlarged"))
						{
							image.animate(large);
							image.data("enlarged",true);
						}
						else
						{
							image.animate(small);
							image.data("enlarged",false);
						}
					});
				}
				
				image.data("click_attached", true);
			}			
			
			function fetch_from_twitpic_server()
			{
				image_parent.find(".loading")
					.attr("class","alert")
					.css("display","block")
					.html("<p>" + S.twitpic_image_move + tt.icons.loading + "</p>");

				var ajax_options = C.ajax_options;
				ajax_options.url = "/get_twitpic/" + entry_id +  ".json";
				ajax_options.success = function(data){
					var parent = $("div[entry_id=" + data.entry_id + "]");
					var image = parent.find(".c_entry-image img");
					image.attr("src",data.image_url);
					image.load(function(){
						parent.find(".alert").remove();
					});
				};
				
				$.ajax(ajax_options);
				
			}
			
			image.attr("src", image.attr("src"));
			image.load(adjust_image);	
			image.error(fetch_from_twitpic_server);
		}
		
		
		//content stream div mouseover handle
		t.mouseover(function(){
			report.show();
			admin_actions.visible();
		});

		//content stream div mouseout handle
		t.mouseout(function(){
			report.hide();
			admin_actions.invisible();
		});
		
		//report button click handler
		if($cheddr.is_logged_in())
		{
			report.one("click",function(){
					var reportedClass = "reported";
					var ajax_options = C.ajax_options;

	        var entry_id = t.find('div.twitter-user').attr('entry_id');
	        ajax_options.url = "/entries/flag/" + entry_id + ".json";

					ajax_options.success = function(data){
						if (data.success)
						{
							simpleLinkToggleActions({trggr:report,tgglcls:reportedClass,hasclstext:S.reportAfter,noclstext:S.reportBefore});				
						}
						else
						{
							alert(data.message);
						}
					}

					$.ajax(ajax_options);
			});
		}
		else
		{
			report.click(function(){
				force_twitter_login({target:$("body"),action_type:"report"});
			});			
		}
		
		//Like button click handler
		if($cheddr.is_logged_in())
		{
			vote.one("click", function(){
				var likedClass = "liked";
				var ajax_options = C.ajax_options;
		     var entry_id = t.find('div.twitter-user').attr('entry_id');
		     ajax_options.url = "/entries/vote_for/" + entry_id + ".json";
				//ajax_options.url = replaceEndPath(location.pathname, 'enter.json'); //Ken, please change this to vote url: http://new.cheddr-pages.com:4000/entries/vote_against/1000.json
				ajax_options.success = function(data){
					if (data.success)
					{
						simpleLinkToggleActions({trggr:vote,tgglcls:likedClass,hasclstext:S.voteAfter,noclstext:S.voteBefore});
						updateVoteCount();
					}
					else
					{
						alert(data.message);
					}
					
					function updateVoteCount()
					{
						//[[vote-count]]: data.net_vote_count always returns "0", please make sure it returns the actual count
						var html = vote.html().replace(/\(\d+\)/,"(" + data.net_vote_count + ")");
						vote.html(html);
					}
					
				}
				$.ajax(ajax_options);
			});
		}
		else
		{
			vote.click(function(){
				force_twitter_login({target:$("body"),action_type:"vote"});
			});
		}

		//Reply button click handler
		
		
		reply.each(function(){
			$(this).click(
				function(){
					bind_reply_action($(this));
			});
		});
		
		function bind_reply_action(reply){
			if(t.data("retweeting"))
			{
				t.find(".retweet-box").remove();
				t.data("retweeting",false);
			}
			var data = {};
			if (!t.data("replying")) {
				if (reply.parent().parent().attr("class")=="comment-actions")
				{
					data.heading = "Reply @" + reply.parents(".a_comment").find(".screen-name").html();
				}
				else
				{
	          data.heading = "Reply @" + user.screenName;
				}
				var insert_target = "";
						
				if (t.find(".a_inline-tweet-box").length==0) {
					t.find(">.p_cs").append("<div class='a_inline-tweet-box a_itb'></div>");
					insert_target = t.find(">.p_cs .a_inline-tweet-box");
				}
				else {
					insert_target = t.find(".a_inline-tweet-box");
				}

        function on_pre_insert(tweetbox) {
          var the_form = tweetbox.find('form');
          tweetbox.find('form').attr('action', replaceEndPath(location.pathname, 'authorize.html'));
          var screen_name = insert_target.siblings().find('a.screen-name:first-child').html();
          var entry_text = "";
					var tweet_box_parent = reply.parents(".a_comment");
					
					if (tweet_box_parent.length > 0)
					{
						entry_text = '@' + tweet_box_parent.find(".screen-name").html() + " ";
					}
					else
					{
						entry_text = '@' + screen_name + ' ';
					}
          
					tweetbox.find('textarea').attr('value', entry_text);
          tweetbox.find( "input[type='submit']").click(function(){
            console.log('reply submit clicked!');
            var entry_id = tweetbox.parent().parent().parent().find('div.twitter-user').attr('entry_id');
            var hidden = $('<input type="hidden">');
            the_form.append(hidden);
            hidden.attr('name','entry[in_reply_to]');
            hidden.attr('value',entry_id);
          });
					tweetbox.data("inlineMode", true);
				}

        data['entry'] = 'foo';
        data['url'] = 'foo';
        data['screen_name'] = 'foo';
        data['avatar'] = 'foo';

				populate({
					data:data,
					insert_type:"append",
					insert_target:insert_target,
					template_id:"t_tweet-box",
					initialization_function:tt.init.a_tweet_box,
					on_pre_insert:on_pre_insert
				});
			
				t.addClass("has_comments");
				t.find("textarea").focus();
				t.data("replying",true);
			}
			else {
				t.find(".a_inline-tweet-box").remove();
				if (t.find(".a_inline-comments").length == 0)
				{
					t.removeClass("has_comments");
				}
				t.data("replying",false);
			}
		}		
	
		//Retweet button click handler
		retweet.each(function(){
			$(this).click(function(){
				bind_retweet_action($(this));
			});
		});
		
		function bind_retweet_action(retweet){
			var insert_target = "";
			var entry_text = "";
			
			if (!t.data("retweeting"))
			{
				t.addClass("has_comments");
				//Remove reply box if it's open
				if(t.data("replying"))
				{
					t.find(".a_tweet-box").remove();
					t.data("replying",false);
				}
				
				if (t.find(".a_inline-tweet-box").length==0) {
					t.find(">.p_cs").append("<div class='a_inline-tweet-box a_itb'></div>");
					insert_target = t.find(">.p_cs .a_inline-tweet-box");
				}
				else {
					insert_target = t.find(".a_inline-tweet-box");
				}
				var screen_name;

				if (retweet.parent().parent().attr("class")=="comment-actions")
				{
					screen_name = retweet.parents(".a_comment").find(".screen-name").html();
					entry_text = 'RT @' + screen_name + " " + retweet.parents(".a_comment").find(".body").text();
				}
				else
				{
	        screen_name = t.find('>.p_cs>.vcard a.screen-name').text();
					entry_text = 'RT @' + screen_name + ' ' + t.find(".twitter-user .entry_body").text().replace(/http:\/\/bit\.ly\/[a-z0-9]+/i,'').trim();
				}



				data = {
					heading: S.retweet + " @" +screen_name,
					url:"foo",
					screen_name:screen_name,
					avatar:"foo",
					entry:"foo"
				};

				populate({
					data:data,
					insert_type:"append",
					insert_target:insert_target,
					template_id:"t_tweet-box",
					initialization_function:tt.init.a_retweet_box,
					on_pre_insert:function(tweet_box){
						tweet_box.addClass("retweet-box");
						tweet_box.find("textarea").attr("value",entry_text);
					}
				});
			
				t.find("textarea").focus();
				t.data("retweeting",true);
			}
			else
			{
				t.data("retweeting",false);
				if (t.find(".a_inline-comments").length == 0)
				{
					t.removeClass("has_comments");
				}
				t.find(".a_inline-tweet-box").remove();
			}
		}
	
		 //Setting comments (only show the latest 3 comments).
		if(number_of_comments > 3)
		{
			var hidden_comments = comments.slice(0,number_of_comments-3);
			var div = t.find(".c_show-more-entries");

			if (div.length == 0) //client side
			{
				hidden_comments.addClass("more_comments");
				div = $("<div class='c_show-more-entries'><a href='javascript:;'>see all " + number_of_comments + " replies...</a></div>");
				div.insertBefore(hidden_comments.slice(0,1));
			}

			var show_more = div.find("a");
			
			show_more.click(function(){
				hidden_comments.removeClass("more_comments");
				div.remove();
			});
		}


	}
  tt.init.load_more_entries = function()
  {
            
  	var trigger = $(".c_lme");
  	trigger.click(function(){
          $cheddr['page_data']['entries']['page'] = $cheddr['page_data']['entries']['page'] + 1;  // Increment to next page
        
  		trigger.find(".i00").removeClass("reload").addClass("ajax-reload");
       //if ($cheddr['page_data']['entries']['oldest_entry_id'] == -1)
       //  return false;
       var get_before_path;
       if (location.pathname == '/')
         get_before_path = 'page/' + $cheddr['page_data']['entries']['page'] + '.json';

         //get_before_path = 'get/before/'+ $cheddr['page_data']['entries']['oldest_entry_id'] + '.json';
       else
          get_before_path = 'page/' + $cheddr['page_data']['entries']['page'] + '.json';
         //get_before_path = 'page/' + $cheddr['page_data']['filter']['id'] + '/' + $cheddr['page_data']['entries']['page'] + '.json';
         //get_before_path = 'get/'+ $cheddr['page_data']['filter']['id'] +'/before/'+ $cheddr['page_data']['entries']['oldest_entry_id'] + '.json';
   
       var options ={
         url:replaceEndPath(location.pathname, get_before_path ),
  			type:"GET",
  			dataType:"json",
  			success:handle_load_more,
  			error:handle_error
  		};
   
  		$.ajax(options);
	
  		function handle_error(xhr)
  		{
  			$("#p_content_streams").append("<div class='error'>" + S.ajaxError + "</div>");
  			trigger.remove();
  		}
	
  		function handle_load_more(data)
  		{
         
         var number_of_entry = data.length;
         if (data && (number_of_entry>0)){
             //$cheddr['page_data']['entries']['page'] = $cheddr['page_data']['entries']['page'] + 1;
           //$cheddr['page_data']['entries']['oldest_entry_id'] = jQuery.map(data, function (a) { return a['id']; }).min();
         }
         else {
           //$cheddr['page_data']['entries']['oldest_entry_id'] = -1;
  				 $("#p_content_streams").append("<div class='alert'>"+ S.ajaxShownAll +"</div>");
  				 trigger.remove();
           return false;
         }
         
        
        for (var i=0;i<number_of_entry;i++)
  			{
  			  if (data[i]===null)
  			  {
  			    stop_loading();
  			    return
  			  }
  				var populate_comments = function(){};
  				var render_entry_image = function(){};
  				var number_of_comments = data[i].comments.length;
			
  				if (number_of_comments > 0)
  				{
  					var comments = data[i].comments;
  					populate_comments = function(content_stream){
  						comments_container = $("<div class='a_inline-comments'></div>");

  							content_stream.find(".p_cs").append(comments_container);
  						content_stream.addClass("has_comments");

  						for (var j=0; j<number_of_comments; j++)
  						{
  				      populate({
  				        data:comments[j],
  				        insert_type:"append",
  				        insert_target:comments_container,
  				        template_id:"t_comment",
  				        initialization_function:function(){},
  				        on_pre_insert:function(){}
  				      });
  						}
  					}
  				}

  				if (data[i].has_image)
  				{
  					data[i].entry_image_url = data[i].image_path;
  					render_entry_image = function(content_stream){
  						var vcard = content_stream.find(".vcard");
  			      populate({
  			        data:data[i],
  			        insert_type:"append",
  			        insert_target:vcard,
  			        template_id:"t_entry-image",
  			        initialization_function:function(){},
  			        on_pre_insert:function(){}
  			      });
  					}
  				}


  				on_pre_insert = function(content_stream){
  					render_entry_image(content_stream);
  					populate_comments(content_stream);
  				}

			    //{hedley:todo2}=> remove this when your ajax return a json that has .tags in it}
			    data[i].tags = "temp";
			    
  	      populate({
  	        data:data[i],
  	        insert_type:"append",
  	        insert_target:$("#p_content_streams"),
  	        template_id:"t_content-stream",
  	        initialization_function:tt.init.a_content_stream,
  	        on_pre_insert:on_pre_insert
  	      });
  			}
  			stop_loading();
  			function stop_loading(){
  			  trigger.find(".i00").removeClass("ajax-reload").addClass("reload");
  			}
  		}

  		return false;
  	});
  }
//********** end:init functions ***********//

	//Utilities
	function simpleLinkToggleActions(arg)
	{
		var trggr = arg.trggr;
		var tgglcls = arg.tgglcls;
		var hasclstext = arg.hasclstext;
		var noclstext = arg.noclstext;
		var html = trggr.html();
		var finalText = (trggr.hasClass(tgglcls))?html.replace(hasclstext,noclstext):html.replace(noclstext,hasclstext);
		trggr.toggleClass(tgglcls);
		trggr.html(finalText);
	}
	
	// TODO: refactor this function and make it more flexible
	function populate(arg)
	{
		post_insert = arg.on_post_insert || function(){};

		var content = $(tmpl(arg.template_id,arg.data));
		arg.on_pre_insert(content); //final operations before the content got inserted to the DOM
    arg.initialization_function(content); //initialize any dynamic elements
		arg.insert_target[arg.insert_type](content);

		// execution
		post_insert(content);
	}
	
	function set_up_textarea_limit(arg)
	{
		var target = arg.target;
		var commonParent = arg.commonParent;
		var limit = arg.limit;
		var charsLeft = "<div class='charsLeft'></div>";
		target.append(charsLeft);
		target.find("textarea").limit(limit, commonParent);
	}

	function ajax_screen(arg)
	{
		var target = arg.target;
		var the_screen = $("<div class='ajax_screen'>&nbsp;</div>");
		var the_message = $("<div class='ajax_screen_message'><b class='i00 ajax_load'>&nbsp</b>Loading...</div>");
		the_screen.css({
			top:0,left:0,position:"absolute",zIndex:100,
			width: target.width(),
			height: target.height(),
			background:"#fff",
			opacity:".7",
			filter:"alpha(opacity=70)"
		});

		the_message.css({
			top:"50%",left:"50%",position:"absolute",zIndex:101,
			width:200,
			height:20,
			marginLeft:-100,
			marginTop:-10,
			textAlign:"center"
		});
		
		target.append(the_screen);
		target.append(the_message);
		
		target.data("off",function(){
			the_message.remove();
			the_screen.remove();
		});
	}
	
	function force_twitter_login(arg)
	{
		var sign_in_box = $(".c_sign-in-box");
		sign_in_box.remove();
		
		//TODOFORKEN: move this to a partial later on
		sign_in_box = $("<div class='c_sign-in-box sm_popup-box'>" + 
											"<h3>You must sign in to " + arg.action_type + "...</h3>" +
											"<a href='javascript:;' class='sign_in action'><b class='i16 twtr'>&nbsp;</b>Sign in with Twitter</a>" +
											"<a href='javascript:;' class='close'>x</a>" +
											"<form></form>" +
										"</div>");

		sign_in_box.find("a.sign_in").click(function(e){
			var form = sign_in_box.find('form');
      form.attr('action', replaceEndPath(location.pathname, 'authorize.html'));
      form.submit();
			return false;
		});
		
		sign_in_box.find("a.close").click(function(){
			sign_in_box.remove();
		});

		arg.target.append(sign_in_box);
	}
	
	function confirm_action(arg)
	{
		var confirm_box = $(".confirm_box");
		confirm_box.remove();
		
		confirm_box = $("<div class='sm_popup-box confirm_box'>" +
											"<h3>" + arg.primary_message + "<span>" + arg.secondary_message + "</span></h3>" +
											"<div class='action_buttons'>" + 
												"<a href='javascript:;' class='yes action'>Yes</a> <a href='javascript:;' class='no action'>No</a>" +
											"</div>" +
										"</div>");

		var yes = confirm_box.find(".yes");
		var no = confirm_box.find(".no");

		arg.no = arg.no || function(){
													confirm_box.remove();
												};
		
		yes.click(function(){
				arg.yes();
				confirm_box.remove();
		});
		no.click(function(){arg.no(confirm_box)});
		
		arg.target.append(confirm_box);
	}

})();

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
	  try {
      var fn = !/\</.test(str) ? //If str doesn't have "<", then str is the id of the template
      cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        	// Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
					.replace("//<![CDATA[","")
					.replace("//]]>","")
          .replace(/[\r\t\n]/g, " ")
					.replace(/<!--.*?-->/g,"")
          .split("<#").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)#>/g, "',$1,'")
          .split("\t").join("');")
          .split("#>").join("p.push('")
          .split("\r").join("\\'")

      + "');}return p.join('');");
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
    }
    catch (suck) {
			alert('error binding template: ' + suck);
			alert(str);
		}
  };
})();

// On document ready, do these:
$(function(){
  if ($cheddr.is_logged_in()) {
    $cheddr.loginLink.parent().hide();
    $cheddr.logoutLink.parent().show();
    $cheddr.logoutLink.click(function(){
      if (logOut()) {	$(this).parent().hide(); }
      else { alert("failed to logout.") }
      $cheddr.loginLink.parent().show();
      function logOut() {
        window.location = '/logout.html?redirect_to='+encodeURIComponent(window.location);
        return true;
      }
      return false;
    });

  }
  else {
    $cheddr.loginLink.click(function(){
      alert('clicked');
      $cheddr.entryForm.find('textarea').attr('name','foo');
      $cheddr.entryForm.attr('action', replaceEndPath(location.pathname, 'authorize.html'));
      $cheddr.entryForm.submit();
      return false;
    });
  }
  tt.init.a_tweet_box($(".a_tweet-box"));
	tt.init.c_lia();

});


