$.fn.replace = function(o) { return this.after(o).remove(); }; 
function linkify(s) {
       var entities = {
           '"' : '&quot;',
           '&' : '&amp;',
           '<' : '&lt;',
           '>' : '&gt;'
       };
       
       return s.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(m) {
           return m.link(m);
       }).replace(/(^|[^\w])(@[\d\w\-]+)/g, function(d, m1, m2) {
           return m1 + "@<a target='_blank' href='http://twitter.com/" + m2.substr(1) + "'>" + m2.substr(1) + '</a>';
       }).replace(/"&<>/, function (m) {
           return entities[m];
       });
};

$(document).ready(function() {
  
  $('form.one_submit').submit(function(){
      // On submit disable its submit button
      $('input[type=submit]', this).attr('disabled', 'disabled');
      $('button[type=submit]', this).attr('disabled', 'disabled');
  });
  /*signin popup*/
  $(function(){
    var pos = $("#signin").offset();  
    var width = $("#signin").width();
    $("#login_reminder").css( { "left": (pos.left) + "px", "top":(pos.top -89) + "px" } ); 
    $("#login_reminder").fadeIn(2000);
  });
  /*reorder groups*/
  $(function() {
	  $("#sortable").sortable({
	    update: function(event, ui) {
	      $.ajax({
        		  type: "PUT",
        		  url: "/groups",
        		  data: $(this).sortable('serialize')
        });}
	  });
	  $("#sortable").disableSelection();  
  });
  /*load friends*/
  if ($(".js_friend_fetch").length != 0)
  {
    $("#followers").load("/friends/1", function(){
      $(".load_more_friends").live("click",function(){
        var p = this.id;
        var url = "/friends/"+p;
        $("#followers").load(url, function(){
          $(".friend_drag").draggable({ 
            revert: 'invalid', 
            start: function(event, ui) {
              $(this).find("div.exta_info").addClass("hide");
            }
           });
        });
      });
      $(".friend_drag").draggable({ 
        revert: 'invalid', 
        start: function(event, ui) {
          $(this).find("div.exta_info").addClass("hide");
        }
       });
    });
  }
  /*drag/drop friends on groups*/
  $(function() {
    $(".friend_drop").droppable({
      accept: ".friend_drag",
      hoverClass: 'friend_hover',
      drop: function(event, ui) {
        var group_id = $(this).attr("id").substr(7);
        var user_id = $(ui.draggable).attr("id");
        var url = "/manage_group/" + group_id;
        var the_li = $(this);
        $.ajax({
            url: url,
            type: "POST",
            data: "user[name]=" + user_id,
            success: function(){
               $(ui.draggable).effect("drop");
               the_li.effect("highlight")
            }
        }); 
      }
    });
  });
  /*remove user from group*/
  $(".delete-button").click(function(){
    var element = $(this).parent().parent();
    var del_val = element.attr("id");
    var del_group = element.attr("class");
    $.ajax({
    		  type: "DELETE",
    		  url: "/manage_group/"+ del_group +"/"+del_val,
    		  success: function(){
    		    element.fadeOut("slow");
    		  }
    });
  });
  /*unfollow user*/
  $(".unfollow-button").live("click",function(){
    var element = $(this).parent();
    var del_val = element.attr("id");
    $.ajax({
    		  type: "POST",
    		  url: "/unfollow/"+del_val,
    		  success: function(){
    		    element.fadeOut("slow");
    		  }
    });
  });
  /*is following check*/
  $(".check_friend").live("click",function(){
    var element = $(this).parent();
    var link = $(this);
    var f_val = element.attr("id");
    $.ajax({
    		  type: "POST",
    		  url: "/check_friend/"+f_val,
    		  success: function(responce){
    		    if (responce == 'true'){
    		      var txt = "<p class='following'>Yes!</p>"
    		    }
    		    else{
    		      var txt = "<p class='not_following'>No</p>"
    		    }
    		    link.replace(txt);
    		  }
    });
  });

  /*hide menu items and show a ff like drop down*/
  $(function() {
    var width = 0;
    $('#menu li').each(function(){
      width += $(this).width();
      if (width > 875) {
       $(this).hide();
       $(this).addClass("show_more")
      }
    });
    if (width < 875){
      $("#show_more_tabs").hide();
    }
  });
  /*more tabs on menue*/
  $("#show_more_tabs").live("click",function(){
    $(".show_more").toggle();
  });
  /*load tweets*/
  $(".js_load_tweet").each(function(index, domElement){
    // make an ajax all to /tweets/ $this.id, and replace the div with the responce	  
    var x = this;
    var username = this.id;
    if (username.match(/~ad/)) 
    {
     // no ads! yay!
    }
    else if (username.match(/_home/)) {
      var url = "/tweets/" + username;
      $.getJSON(url, function(json){
        var i = 0;       
        var tws = $.map(json, function(n){
        ++i; 
        if (i >10) {
         var hide = "hide"
        }
        else{
          var hide = ''
        }
        return "<li class='tweet "+i+" "+
                hide +
                " '>"+
                "<img title="+ n.screen_name +" src=" + n.mini_profile_image_url + " height='24' width='24' />" + 
                linkify(n.text)+
                " <a target='_blank' href=http://twitter.com/" + n.screen_name + "/status/"+ n.id + ">"+ 
                "<span class='time_ago'>" +
                jQuery.timeago(n.created_at) +
                "</span>" +
                "</a>" +
                "&nbsp; <a class='icon-reply' title='reply to this' id='"+n.id+"' href='#'>"+"@"+ n.screen_name + "</a>" +
                "&nbsp; <a class='icon-retweet' title='retweet' href='#'>"+("RT @" + n.screen_name + " " + n.text)+"</a>" +
                "&nbsp; <a title='favourite tweet' class='icon-fav' href='/fav/"+ n.id +"'>&#x272D;</a>" + 
                "</li>";
        }).join("");
        // replace main element
         $(x).replace("<div id='users=" + username +"' class='js_portlet' name=users[]>" + 
         "<p class='bio js_portlet_head'> Home" +
         "</p>" +
         "<ol class='tweets js_portlet_body'>" +
         tws +
         "</ol>" +
         "</div>");
      });
    }
    else if (username.match(/_mentions/)) {
      var url = "/tweets/" + username;
      $.getJSON(url, function(json){
        var i = 0;       
        var tws = $.map(json, function(n){
        ++i; 
        if (i >6) {
         var hide = "hide"
        }
        else{
          var hide = ''
        }
        return "<li class='tweet "+i+" "+
                hide +
                " '>"+
                "<img title="+ n.screen_name + " src=" + n.mini_profile_image_url + " height='24' width='24' />" + 
                linkify(n.text)+
                " <a target='_blank' href=http://twitter.com/" + n.screen_name + "/status/"+ n.id + ">"+ 
                "<span class='time_ago'>" +
                jQuery.timeago(n.created_at) +
                "</span>" +
                "</a>" +
                "&nbsp; <a class='icon-reply' title='reply to this' id='"+n.id+"' href='#'>"+"@"+ n.screen_name + "</a>" +
                "&nbsp; <a class='icon-retweet' title='retweet' href='#'>"+("RT @" + n.screen_name + " " + n.text)+"</a>" +
                "&nbsp; <a title='favourite tweet' class='icon-fav' href='/fav/"+ n.id +"'>&#x272D;</a>" + 
                "</li>";
        }).join("");
        // replace main element
         $(x).replace("<div id='users=" + username +"' class='js_portlet' name=users[]>" + 
         "<p class='bio js_portlet_head'> Mentions" +
         "</p>" +
         "<ol class='tweets js_portlet_body'>" +
         tws +
         "</ol>" +
         "</div>");
      });
    }
    else if (username.match(/_favorites/)) {
      var url = "/tweets/" + username;
      $.getJSON(url, function(json){
        var i = 0;       
        var tws = $.map(json, function(n){
        ++i; 
        if (i >6) {
         var hide = "hide"
        }
        else{
          var hide = ''
        }
        return "<li class='tweet "+i+" "+
                hide +
                " '>"+
                "<img title="+ n.screen_name +" src=" + n.mini_profile_image_url + " height='24' width='24' />" + 
                linkify(n.text)+
                " <a target='_blank' href=http://twitter.com/" + n.screen_name + "/status/"+ n.id + ">"+ 
                "<span class='time_ago'>" +
                jQuery.timeago(n.created_at) +
                "</span>" +
                "</a>" +
                "&nbsp; <a class='icon-reply' title='reply to this' id='"+n.id+"' href='#'>"+"@"+ n.screen_name + "</a>" +
                "&nbsp; <a class='icon-retweet' title='retweet' href='#'>"+("RT @" + n.screen_name + " " + n.text)+"</a>" +
                "&nbsp; <a title='favourite tweet' class='icon-fav' href='/fav/"+ n.id +"'>&#x272D;</a>" + 
                "</li>";
        }).join("");
        // replace main element
         $(x).replace("<div id='users=" + username +"' class='js_portlet' name=users[]>" + 
         "<p class='bio js_portlet_head'> Favorites" +
         "</p>" +
         "<ol class='tweets js_portlet_body'>" +
         tws +
         "</ol>" +
         "</div>");      });  
    }
    else if (username.match(/_direct_messages/)) {
      var url = "/tweets/" + username;
      $.getJSON(url, function(json){
        var i = 0;       
        var tws = $.map(json, function(n){
        ++i; 
        if (i >6) {
         var hide = "hide"
        }
        else{
          var hide = ''
        }
        return "<li class='tweet "+i+" "+
                hide +
                " '>"+
                "<img title="+ n.screen_name +" src=" + n.mini_profile_image_url + " height='24' width='24' />" + 
                linkify(n.text)+
                " <a href='http://twitter.com/#inbox'><span class='time_ago'>" +
                jQuery.timeago(n.created_at) +
                "</span></a>" +
                " <a href='#' class='icon-dm' title='direct message'>" + n.screen_name + "</a>"+
                "</li>";
        }).join("");
        // replace main element
         $(x).replace("<div id='users=" + username +"' class='js_portlet' name=users[]>" + 
         "<p class='bio js_portlet_head'> Direct messages" +
         "</p>" +
         "<ol class='tweets js_portlet_body'>" +
         tws +
         "</ol>" +
         "</div>");      
      });  
    }
    else
    {
      var url = "/tweets/" + username;
      $.getJSON(url, function(json){
        // console.log(json);
        // collect tweets into a <li> seperated string
        var i = 0;
        var tws = $.map(json.statuses, function(n){
        ++i; 
        if (i >6) {
         var hide = "hide"
        }
        else{
          var hide = ''
        }
        return "<li class='tweet "+i+" "+
                hide +
                " '>"+
                linkify(n.text)+
                " <a target='_blank' href=http://twitter.com/" + json.screen_name + "/status/"+ n.id + ">"+ 
                "<span class='time_ago'>" +
                jQuery.timeago(n.created_at) +
                "</span>" +
                "</a>" +
                "&nbsp; <a class='icon-reply' title='reply to this' id='"+n.id+"' href='#'>"+"@"+ json.screen_name + "</a>" +
                "&nbsp; <a class='icon-retweet' title='retweet' href='#'>"+("RT @" + json.screen_name + " " + n.text)+"</a>" +
                "&nbsp; <a title='favourite tweet' class='icon-fav' href='/fav/"+ n.id +"'>&#x272D;</a>" + 
                "</li>";
        }).join("");

        // replace main element
         $(x).replace("<div id='users=" + json.screen_name +"' class='js_portlet' name=users[]>" + 
         "<p class='bio js_portlet_head'>" +
         "<img src=" + json.mini_profile_image_url + " height='48' width='48' />" + 
         " <a target='_blank' href=http://twitter.com/" + json.screen_name + ">@" + json.screen_name + "</a>" +
         " - " + json.description + " <a href='#' class='icon-dm' title='direct message'>" + json.screen_name + "</a>" +
         "</p>" +
         "<ol class='tweets js_portlet_body'>" +
         tws +
         "</ol>" +
         "</div>");
      });
    }
    
  });
  
  /*retweet*/
  $(".icon-retweet").live("click",function(e){
    $("#reply_to_id").val('');
    $('#to_user').val('');
    $(".thickbox").attr("title", "ReTweet this");
    $(".thickbox").trigger('click');
    var status_text = $(e.target).text();
    $('#status_box').val(status_text);
    $('#status_box').trigger("keyup");
  });
  
  /*reply*/
  $(".icon-reply").live("click",function(e){
    $('#to_user').val('')
    var target = e.target;
    var to_user = $(target).text();
    var tweet_id = $(target).attr("id");
    $(".thickbox").attr("title", "Reply to " + to_user);
    $(".thickbox").trigger('click');
    $("#reply_to_id").val(tweet_id);
    $('#status_box').val(to_user);
    $('#status_box').trigger("keyup");
  });
  
  /*reply*/
  $(".icon-dm").live("click",function(e){
    $("#reply_to_id").val('');
    $('#status_box').val('');
    var target = e.target;
    var to_user = $(target).text();
    $(".thickbox").attr("title", "Direct Message " + to_user);
    $(".thickbox").trigger('click');
    $('#to_user').val(to_user);
  });
  /*reset*/
  $(".thickbox").click(function(){
    $("#reply_to_id").val('');
    $('#status_box').val('');
    $('#to_user').val('');
  });
  
  $('#status_box').twitterCounter({
     limit: 140,
     counter: '#textcounter',
   
     okSize: 140,
     okStyle: '.ok',
   
     watchSize: 20,
     watchStyle: '.watch',
   
     warningSize: 10,
     warningStyle: '.warning',
   
     errorSize: 0,
     errorStyle: '.error',
  });
  
  /*reorder users in the group*/
  $(function() {
		$(".column").sortable({
			connectWith: '.column',
			 update: function(event, ui) {
			   $(this).sortable("refresh");
  	      $.ajax({
          		  type: "PUT",
          		  url: "/reorder/" + $(this).parents().attr('class')+"?column="+$(this).attr('id'),
          		  data: $(this).sortable('serialize', {expression:'(.+)[=](.+)'})
          });}
		});
		$(".column").disableSelection();	

		$(".js_portlet").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			.find(".js_portlet_head")
				.addClass("ui-widget-header ui-corner-all")
				.prepend('<span class="ui-icon ui-icon-plusthick"></span>')
				.end()
			.find(".js_portlet_body");

		$(".js_portlet_head .ui-icon").click(function() {
			$(this).toggleClass("ui-icon-minusthick");
			$(this).parents(".js_portlet:first").find(".js_portlet_body").toggle();
		});

  });
	
});

