(function($) {
	$.fn.stripHtml = function() {
		var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;
		
		return $(this).val().replace(regexp,"[HTML REMOVED]");
	}
})(jQuery);

markdown2html = function(element, text){
	if(text == ''){
		element.hide("slow");
		return;
	}
	
	converter = new Showdown.converter();
	html = converter.makeHtml(text);
	
	html = "<div>\n\t" + html + "\n</div>";
	
	element.html(html);
	element.show();
	
	return true
};

nl2br = function(str) {
	return (str + '').replace(/([^>]?)\n/g, '$1'+ '<br />' +'\n');
}

function getID(id){
    return id.replace(/(\D)/, "")
}

edit_comment_submit = function(target_element, event){
    id = target_element.siblings(".body").children("form").children("input").attr("value");
    body = target_element.siblings(".body").children("form").find("textarea").val();
    
    target_element.siblings(".body").html("<img src=\"/img/ajax_loading.gif\" width=\"16px\" height=\"16px\"/> Submitting");
    
    $.post("/comment/edit", {id: id, body: body}, function(value) {
        var values = eval(value);
                            
        if(values[1] == ''){
            target_element.siblings(".body").html(values[0]);
            target_element.html("edit");
            target_element.removeClass("cancel_edit_comment")
            target_element.addClass("edit_comment")
            
            $("a.edit_comment").unbind().click(function(event){
                edit_comment($(this), event)
                event.preventDefault();
            });
        }
        else{
            target_element.siblings(".body").html("<h4 class=\"error\">" + values[1] + "</h4>" + form);
            target_element.siblings(".body").children("form").find("textarea").val(values[0]);
            
            $("form.edit_comment").submit(function(event){
                edit_comment_submit(target_element, event);
                event.preventDefault();
            });
        }
        
    });
}

edit_comment = function(target_element, event) {
    id = getID(target_element.attr("id"));
    form = "<form class=\"edit_comment\" action=\"#\">    <input name=\"target\" type=\"hidden\" value=\""+ id + "\"/>    <textarea name=comment cols=\"100\" rows=\"5\"></textarea><br />    <input name=\"commit\" type=\"submit\" value=\"submit\" /></form>"
    target_element.html("cancel");
    target_element.removeClass("edit_comment")
    target_element.addClass("cancel_edit_comment")
    
    comment = target_element.siblings(".body").text();
                    
    target_element.siblings(".body").html(form);
    target_element.siblings(".body").children("form").find("textarea").val(comment);
    
    $("a.cancel_edit_comment").unbind().click(function(event){
        cancel_edit_comment($(this), event);
        event.preventDefault();
    });
    $("form.edit_comment").submit(function(event){
        edit_comment_submit(target_element, event);
        event.preventDefault();
    });
}

cancel_edit_comment = function(target_element, event) {
                    
    target_element.html("edit");
    target_element.removeClass("cancel_edit_comment")
    target_element.addClass("edit_comment")
    
    id = getID(target_element.attr("id"));
    html = target_element.siblings("div.body").html();
    target_element.html("edit");
    target_element.siblings(".body").html(target_element.siblings(".body").children("form").find("textarea").val());
    
    $("a.edit_comment").unbind().click(function(event){
        edit_comment($(this), event)
        event.preventDefault();
    });
}

count_updating = function(){
	var message_count = false;
	var friend_requests = false;
	
	user_id = $(".loggedin").attr("name");
	
	if($(".message_count")){
		message_count = true;
	};
	
	if($(".friendrequest_count")){
		friend_requests = true;
	};
	
	/*alert(user_id);
	alert(message_count);
	alert(friend_requests);*/
	if(user_id){
		$.post("/ajax/count_update", {user_id: user_id, message: message_count, friend_request: friend_requests}, function(value){
			var data = eval("(" + value + ")");
					
			$(".message_count").each(function(value){
				$(this).html(String(data['message_count']));
			});
			
			$(".friendrequest_count").each(function(value){
				$(this).html(String(data['friend_request_count']));
			});
		});
	};
}

no_friends = function(id){
	row = $("div#"+id)
	siblings = row.siblings()
	parent = row.parent()
	
	if(siblings.length > 0){
		row.remove();
	}
	else{
		parent.append("<div class=\"friend_request\" align=\"center\">\n\t<h1>No Friend Requests</h1>\n</div>");
		row.remove();
	};
	
}

create_lightbox = function(holder, html){
    var ph = $(this).height();
    var pw = $(this).width();
    
    holder.html(html);
    
    holder.children().each(function(event){
        var margintop = (ph - $(this).height())/2
        var left = (pw - $(this).width())/2
        
        if (left < 0) {
            left = 0;
        }
        if (margintop < 0) {
            margintop = 0;
        }
        
        $(this).css('position', "fixed");
        $(this).css('margin-top', margintop);
        $(this).css("left", left);
    });
}

jQuery(function() {
	
	count_updating();
	var count_intervalId = setInterval ( "count_updating()", 30000 );
	
	$(".help").live('mouseover', function(event){
		var text = $(this).attr("alt")
		
		position = $(this).position()
		$("body").append("<div id=\"help_bubble\">" + text + "</div>")
		var bubble = $("#help_bubble")
		bubble.css('left', position.left + $(this).width());
		bubble.css('top', position.top);
		
	})
	$(".help").live('mouseout', function(event){
		$("#help_bubble").remove();
	})
	$(".help").live('click', function(event){
	});
	
	$("input.username").click(function(event){
		if($(this).val() == "Username"){
			$(this).val("");
		}
	});
	
	$("input.username").blur(function(event){
		if($(this).val() == ""){
			$(this).val("Username");
		}
	});
	
    $("a.edit_comment").click(function(event) {
        edit_comment($(this), event);
        event.preventDefault();
    });
    
    $("a.favorite").click(function(event) {
        make_favorite($(this), event)
        
        event.preventDefault();
    });
    
    $("a.favorite_selected").click(function(event) {
        remove_favorite($(this), event)
                
        event.preventDefault();
    });
    
    $("input.receiver").focus(function(event){
		if($(this).val() == 'person to message'){
			$(this).val('');
		}
        event.preventDefault();
    });
	$("input.receiver").blur(function(event){
		
		if ($(this).val() == ''){
			$(this).val('person to message');
		}
		
        event.preventDefault();
    });
	
	$("textarea.new").focus(function(event){
		if($(this).val() == 'enter your message ...'){
			$(this).val('');
		}
        event.preventDefault();
    });
	$("textarea.new").blur(function(event){
		if ($(this).val() == ''){
			$(this).val('enter your message ...');
		}
		
        event.preventDefault();
    });
    
	$("a.x").click(function(event){
		var id = $(this).attr("href");
		var parent = $(this).parents(".friend");
		var friend_count = parseInt($("b#friend_count").html());
		
		var siblings = parent.siblings()
		
		if(confirm("Break this relationship?")){
			$.post("/ajax/break_friendship", {them: id}, function(value) {
				parent.fadeOut("slow", function(event){
					friend_count = friend_count - 1
					
					$("b#friend_count").html(friend_count);
					
					if(friend_count == 0){
						$("b#friend_count").html("0");
						parent.parent().append("<div class=\"friend_request\" align=\"center\">\n\t<h1 align=\"center\">No Friends</h1>\n</div>");
					}
					parent.remove();
					
					var i = 1;
					siblings.removeClass("last");
					siblings.each(function(){
						if(i%3==0){
							$(this).addClass("last")
						}
						i++
					})
					
				});
				
				
				
			});
		}
        event.preventDefault();
	});
	
	$(".mdf div.comment_body").live("mouseover", function(event){
		$(this).css("color", "#cccccc");
		$(this).css("cursor", "pointer")
	});
	
	$(".mdf div.comment_body").live("mouseout", function(event){
		$(this).css("color", "");
		$(this).css("cursor", "default");
	});
	
	$(".mdf div.comment_body").live("click", function(event){
		id = $(this).attr("id");
		comment_id = $(this).attr("name")
		url = "/comment/" + id + "/" + comment_id
		window.location = url
	});
	
	
	$(".lightbox").live("click", function(event) {
        event.preventDefault();
        
        var href = $(this).attr("href");
        
        $("#holder").each(function(){
            var holder = $(this);
            var ph = $(this).height();
            var pw = $(this).width();
            
            holder.transBGdraw({'z-index':'5', 'background-color':'#000000', 'opacity':'0.20'});
                        
            if(href != ''){
                $.post(href, {}, function(value){
                    
                    create_lightbox(holder, value);
                    
                });
                
                holder.fadeIn('slow');
            }
            
        });
        
    });
    $(".close_lightbox").live("click", function(event){
        event.preventDefault();
        closeLightbox();
    })
});

function closeLightbox() {
    $("#holder").fadeOut();
    $("#holderTransBG").remove();
}

function areArraysEqual(array1, array2) {
   var temp = new Array();
   if ( (!array1[0]) || (!array2[0]) ) { // If either is not an array
      return false;
   }
   if (array1.length != array2.length) {
      return false;
   }
   // Put all the elements from array1 into a "tagged" array
   for (var i=0; i<array1.length; i++) {
      key = (typeof array1[i]) + "~" + array1[i];
   // Use "typeof" so a number 1 isn't equal to a string "1".
      if (temp[key]) { temp[key]++; } else { temp[key] = 1; }
   // temp[key] = # of occurrences of the value (so an element could appear multiple times)
   }
   // Go through array2 - if same tag missing in "tagged" array, not equal
   for (var i=0; i<array2.length; i++) {
      key = (typeof array2[i]) + "~" + array2[i];
      if (temp[key]) {
         if (temp[key] == 0) { return false; } else { temp[key]--; }
      // Subtract to keep track of # of appearances in array2
      } else { // Key didn't appear in array1, arrays are not equal.
         return false;
      }
   }
   // If we get to this point, then every generated key in array1 showed up the exact same
   // number of times in array2, so the arrays are equal.
   return true;
}
