// Use jQuery via $j(...)
var $j = jQuery.noConflict();

function ajaxEffect(content){
	$j(content).css({visibility:"hidden"}).fadeIn(1000).css({visibility:"visible"}).animate({opacity: 1.0}, 3000).fadeOut(1000);
}

function ajaxEffectIn(content){
	$j(content).css({visibility:"hidden"}).fadeIn(1000).css({visibility:"visible"});
}

$j(document).ready(function() {
  $j('#toggleheadline').show();
  $j('#oldcomments').hide();
  
  $j('a#toggle').click(function() {
    $j('#oldcomments').toggle(500);
    $j('#toggleheadline').fadeOut(1000);
    return false;
  });

	var scripts = $j(document).find("script");
	for ( i = 0; i <= scripts.length; i++ ) {
		var scriptSrc = $j(scripts[i]).attr("src");
		var result = scriptSrc.match(/http:(.*)jquery-comments.js/);
		if ( result ) break;
	}
	ajaxURL = result[0].replace(/jquery-comments.js/, "jquery-ajax.php");

  $j('#comment').one('focus',function() { //Live Comments
    $j('#comment').parent().after('<div id="live-preview"></div>');
  });
  
  var $comment = ''; // that's two single quotation-marks at the end
  $j('#comment').keyup(function() {
    $comment = $j(this).val();
    $comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />').replace(/(<\/?)script/g,"$1noscript");
    $j('#live-preview').html( $comment );
  });

	$j("#commentform").submit(function(){
		if ( $j.find("#commentlist") == "" )	$j(".comments_div").append('<ol id="commentlist"></ol>');
		$j("#submit").before('<p id="comment-loading">&nbsp;</p>');
		ajaxEffectIn("#comment-loading");
		$j.ajax({
			type: "POST",
			url: ajaxURL,
			data: $j("#commentform input, #commentform textarea").serialize(),
			dataType: "html",
			error: function(request){
				if ($j("#ajaxerror")) $j("#ajaxerror").remove();
				$j("#comment-loading").fadeOut(1000, function(){
					$j("#comment-loading").remove();
					if (request.responseText.search(/<title>WordPress &rsaquo; Error<\/title>/) != -1) {
						var data = request.responseText.match(/<p>(.*)<\/p>/);
						data = '<p id="ajaxerror">Error: ' + data[1] + '</p>';
					} else {
						var data = request.responseText;
					}
					$j("#respond").append(data);
					ajaxEffect("#ajaxerror");
				});
			},
			success: function(data){
				if ($j("#ajaxerror")) $j("#ajaxerror").remove();
				$j("#comment-loading").fadeOut(1000, function(){
					$j("#comment-loading").remove();
					$j(".comments_div").append(data);
					ajaxEffectIn("#newcomment");
					$j(".comment_div").animate({opacity: 1.0}, 1500).fadeOut(2000);
				});
			}
		});
		return false;
	});

});

