window.onbeforeunload = function ( e ) {
	if(jQuery('#posttext').val() || jQuery('#comment').val() == true) {
  		var e = e || window.event;
  		if ( e ) {   // For IE and Firefox
    		e.returnValue = ThreadedCommentstxt.unsaved_changes;
  		}
  		return ThreadedCommentstxt.unsaved_changes;   // For Safari
	}
};

jQuery(function($) {
	/*
	* Insert new comment inline
	*/
	function insertCommentInline(comment_parent, commentHtml, showNotification) {
		var commentBGColor = commentEvenRowColor;
    
    comment_parent = $(comment_parent);
    if(comment_parent.get(0).tagName=='LI'){
//      alert(comment_parent.get(0).tagName);
      
      if ( 0 == comment_parent.children('ul.children').length) {
        comment_parent.append('<ul class="children"></ul>');
      }
      comment_parent = comment_parent.children('ul.children');

    }

    var prevLi;
//    alert(commentBGColor);
    if(commentsSortOrder=="asc"){
      prevLi = comment_parent.children("li.comment:last");
//      console.log(prevLi);
      if(prevLi.hasClass("even")){
//        console.log(commentBGColor);
        commentBGColor = commentOddRowColor;
      }

      comment_parent.append('<div class="temp_newComments_cnt"></div>');
    }else{
      prevLi = comment_parent.children("li.comment:first");
      if(prevLi.hasClass("even")){
        commentBGColor = commentOddRowColor;
      }

      comment_parent.prepend('<div class="temp_newComments_cnt"></div>');
    }
    
    if(!prevLi.length){
      if(comment_parent.parent("li.comment").length && comment_parent.parent("li.comment").hasClass("even")){
        commentBGColor = commentOddRowColor;
      }
    }
    //console.log(comment_parent.parent("li.comment"));
    
    var newComment =  comment_parent.children('div.temp_newComments_cnt');

		newComment.html(commentHtml);
		var newCommentsLi = newComment.children('li');
		newCommentsLi.addClass("newcomment");
//		newCommentsLi.css("background-color", "transparent");
		newCommentsLi.show();
		var cnt = newComment.contents();
		newComment.children('li.newcomment').each(function() {
			if (isElementVisible(this)) {
        $(this).stop();
//        console.log(commentBGColor);

        $(this).toggleClass("odd", commentBGColor == commentOddRowColor);
        $(this).toggleClass("even", commentBGColor == commentEvenRowColor);
        $(this).toggleClass("animating");
//        console.log(commentBGColor);
				$(this).children("div.colored-div").animate({backgroundColor:commentBGColor},commentBGColorTime, function(){
					$(this).parent("li").removeClass('newcomment');
          $(this).attr("style", "background-color:"+commentBGColor+";");
          $(this).parent("li").toggleClass("animating");
				});
			}
			bindActions(this, 'comment');
		});
		newComment.replaceWith(cnt);
	}

	/*
	* Check for new comments and loads them inline and into the recent-comments widgets
	*/
	function getComments(showNotification){
		if (showNotification !== false) {
			showNotification = true;
		}
		toggleUpdates('unewcomments');
		var queryString = 'load_time=' + pageLoadTime + '&lcwidget=' + lcwidget;
		var ajaxUrl_ = ajaxUrl;
    if(!isUserLoggedIn2){
      queryString ="action=ThreadedComments_latest_comments&" + queryString;
    }else{
      ajaxUrl_ = ajaxUrl + "?action=ThreadedComments_latest_comments"
    }
		queryString += postsOnPageQS;
		ajaxCheckComments = $.post(ajaxUrl_, queryString, function(newComments) {
			if (newComments != 0) {
				$.each(newComments.comments, function(i,comment) {
					pageLoadTime = newComments.lastcommenttime;
					if (comment.widgetHtml) {
						insertCommentWidget(comment.widgetHtml);
					}

          var comment_parent;
					if (comment.html != '') {
            if($("#comment-"+comment.commentParent).length==0){
              comment_parent = $("#comments");
            }else{
              comment_parent = $("#comment-"+comment.commentParent);
            }
						insertCommentInline(comment_parent, comment.html, showNotification);
					}
				});
				if (showNotification) {
					newNotification(ThreadedCommentstxt.n_new_comments.replace('%d', newComments.numberofnewcomments));
				}
			}
		}, "json");
		toggleUpdates('unewcomments');
	}

  function newNotification(message) {
//    alert(message);
//    console.log($("#notify"));
    $("#notify").stop(true).prepend(message + '<br/>')
    .fadeIn()
    .animate({
      opacity: 0.7
    }, 2000)
    .fadeOut('1000', function() {
      $("#notify").html('');
    }).click(function() {
      $(this).stop(true).fadeOut('fast').html('');
    });
  }

	/*
	* Submits a new comment via ajax
	*/
	function newComment(trigger) {
		var thisForm = $(trigger.target);
		var thisFormElements = $('#comment, #comment-submit, #author, #email, #url, :input', thisForm).not('input[type=hidden]');
		var submitProgress = thisForm.find('span.progress');
		var commenttext = $.trim($('#comment').val());
		if ("" == commenttext) {
			$("label#commenttext_error").text('This field is required').show().focus();
			return false;
		}
		toggleUpdates('unewcomments');
		if (typeof ajaxCheckComments != "undefined")
			ajaxCheckComments.abort();
		$("label#commenttext_error").hide();

		thisFormElements.attr('disabled', true);
		thisFormElements.addClass('disabled');

		submitProgress.show();
		var comment_post_ID = $('#comment_post_ID').val();
		var comment_parent = $('#comment_parent').val();
		var dataString = {_ajax_post: nonce, comment: commenttext,  comment_parent: comment_parent, comment_post_ID: comment_post_ID,
                      comment_author: typeof($("#author").val())!="undefined" ? $("#author").val() : "",
                      comment_email: typeof($("#email").val())!="undefined" ? $("#email").val() : "",
                      comment_url: typeof($("#url").val())!="undefined" ? $("#url").val() : ""
                    };

    var ajaxUrl_ = ajaxUrl;
    if(!isUserLoggedIn2){
      dataString["action"] =  'ThreadedComments_new_comment' ;
    }else{
      ajaxUrl_ =ajaxUrl + "?action=ThreadedComments_new_comment";
    }
    
		var errorMessage = '';
		$.ajax({
			type: "POST",
			url: ajaxUrl_,
			data: dataString,
			success: function(result) {
				var lastComment = $("#respond").prev("li");
				if (isNaN(result) || 0 == result || 1 == result)
					errorMessage =result;
				$('#comment').val('');
				if (errorMessage != ""){
          newNotification(errorMessage);
        }else{
          getComments(false);
          $("#respond").slideUp('fast', function(){
            $("#cancel-comment-reply-link").click();
          });
        }

        submitProgress.fadeOut();
        toggleUpdates('unewcomments');
        thisFormElements.attr('disabled', false);
        thisFormElements.removeClass('disabled');

			}
		});
	}

	
	/*
	* Handles tooltips for the recent-comment widget
	* param: anchor link
	*/
	function tooltip(alink){
		xOffset = 10;
		yOffset = 20;
		alink.hover(function(e){
			this.t = this.title;
			this.title = "";
			$("body").append("<div id='tooltip'>"+ this.t +"</div>");
			$("#tooltip")
				.css("top",(e.pageY - yOffset) + "px")
				.css("left",(e.pageX + xOffset) + "px")
				.fadeIn("fast");
	    },
		function(){
			this.title = this.t;
			$("#tooltip").remove();
	    });
		alink.mousemove(function(e){
			$("#tooltip")
				.css("top",(e.pageY - yOffset) + "px")
				.css("left",(e.pageX + xOffset) + "px");
		});
	};

	function isElementVisible(elem) {
	    elem = $(elem);
		if (!elem.length) {
	        return false;
	    }
	    var docViewTop = $(window).scrollTop();
	    var docViewBottom = docViewTop + $(window).height();

	    var elemTop = elem.offset().top;
	    var elemBottom = elemTop + elem.height();
		var isVisible = ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)  && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
	    return isVisible;
	}

	function toggleUpdates(updater){
		switch (updater) {
			case "unewcomments":
				if (0 == getCommentsUpdate) {
					getCommentsUpdate = setInterval(getComments, updateRate);
				}
				else {
					clearInterval(getCommentsUpdate);
					getCommentsUpdate = '0';
				}
				break;
		}
	}

	function titleCount() {
		if (isFirstFrontPage) {
			var n = $('li.newupdates').length;
		} else {
			var n = newUnseenUpdates;
		}
		if ( n <= 0 ) {
			if (document.title.match(/\([\d+]\)/)) {
				document.title = document.title.replace(/(.*)\([\d]+\)(.*)/, "$1$2");
			}
		} else {
			if (document.title.match(/\((\d+)\)/)) {
				document.title = document.title.replace(/\((\d+)\)/ , "(" + n + ")" );
			} else {
				document.title = '(1) ' + document.title;
			}
		}
	}

	function autgrow(textarea, min) {
		var linebreaks = textarea.value.match(/\n/g);
		if (linebreaks != null && linebreaks.length+1 >= min) {
			textarea.rows = (linebreaks.length+1);
		}
		else {
			textarea.rows =  min;
		}
	}
	
	function jumpToTop() {
		$.scrollTo('#comments', 150);
	}

	function bindActions(element, type) {
		switch (type) {
			case "comment" :
				var thisCommentEditArea;
				$(element).hover( removeYellow, removeYellow );
				if (inlineEditComments != 0 && isUserLoggedIn) {
					thisCommentEditArea = $(element).find('div.comment-edit');
					thisCommentEditArea.editable(ajaxUrl, {event: 'edit',loadurl: ajaxUrl + '?action=ThreadedComments_load_comment&_inline_edit=' + nonce,
						id: 'comment_ID', name: 'comment_content', type    : 'autogrow', cssclass: 'textedit', rows: '3',
						indicator : '<img src="' + templateDir +'/i/indicator.gif">', loadtext: ThreadedCommentstxt.loading, cancel: ThreadedCommentstxt.cancel,
						submit  : ThreadedCommentstxt.save, tooltip   : '', width: '90%', onblur: 'ignore',
						submitdata: {action:'ThreadedComments_inline_comment_save',_inline_edit: nonce}});
					$(element).find('a.comment-edit-link').click(function() {
						thisCommentEditArea.trigger("edit");
						return false;
					});
				}
				break;
		}
	}


	/* On-load */
	
	commentsLists = $("ul.commentlist");
	
	$('#posttext').focus();
	
	$(".single #postlist li > div.postcontent, .single #postlist li > h4, li[id^='ThreadedComments'] > div.postcontent, li[id^='comment'] > div.commentcontent, li[id^='ThreadedComments'] > h4, li[id^='comment'] > h4").hover(function() {
		$(this).parents("li").eq(0).addClass('selected');
	}, function() {
		$(this).parents("li").eq(0).removeClass('selected');
	});
	
	$.ajaxSetup({
	  timeout: updateRate - 2000,
	  cache: false
	});
	
	$("#directions-keyboard").click(function(){
		$('#help').toggle();
		return false;
	});
	
	$("#help").click(function() {
		$(this).toggle();
	});
	
	$("#togglecomments").click(function(){
		hidecomments = !hidecomments;
		var hideTxt = ThreadedCommentstxt.hide_threads;
		var showTxt = ThreadedCommentstxt.show_threads;
		if (hidecomments) {
			commentLoop = false;
			commentsLists.hide();
			$(this).text(showTxt);
		} else {
			commentsLists.show();
			$(this).text(hideTxt);
		}
		return false;
	});
	
	//if (!isFrontPage) $("#togglecomments").click();
	
	// Activate inline editing plugin
	if ((inlineEditPosts || inlineEditComments ) && isUserLoggedIn) {
		$.editable.addInputType('autogrow', {
		    element : function(settings, original) {
		        var textarea = $('<textarea />');
		        if (settings.rows) {
		            textarea.attr('rows', settings.rows);
		        } else {
		            textarea.attr('rows', 4);
		        }
		        if (settings.cols) {
		            textarea.attr('cols', settings.cols);
		        } else {
		            textarea.attr('cols', 45);
		        }
				textarea.width('95%');
		        $(this).append(textarea);
		        return(textarea);
		    },
		    plugin : function(settings, original) {
		        $('textarea', this).keypress(function(e) {autgrow(this, 3);});
		        $('textarea', this).focus(function(e) {autgrow(this, 3);});
		    }
		});
	}
		
	// Set tabindex on all forms
	var tabindex = 4;
	$('form').each(function() {
		$(':input',this).not('input[type=hidden]').each(function() {
        	var $input = $(this);
			var tabname = $input.attr("name");
			var tabnum = $input.attr("tabindex");
			if(tabnum > 0) {
				index = tabnum;
			} else {
				$input.attr("tabindex", tabindex);
			}
			tabindex++;
		});
     });
		
	// Turn on automattic updating	
	if (ThreadedCommentsCommentsUpdates && isUserLoggedIn) {
			toggleUpdates('unewcomments');
	}
	
	// Check which posts are visibles and add to array and comment querystring
	$("span.ajax_content_post_id ").each(function() {
		
		vpostId = $(this).attr("value");
		postsOnPage.push($(this).parent("li"));
		postsOnPageQS += "&vp[]=" + vpostId;
	});

	if (inlineEditComments && isUserLoggedIn) {
		$('div.comment-edit').editable(ajaxUrl, {event: 'edit',loadurl: ajaxUrl + '?action=ThreadedComments_load_comment&_inline_edit=' + nonce,
			id: 'comment_ID',name: 'comment_content', type    : 'autogrow', cssclass: 'textedit', rows: '3',
			indicator : '<img src="' + templateDir +'/i/indicator.gif">', loadtext: ThreadedCommentstxt.loading, cancel: ThreadedCommentstxt.cancel, submit: ThreadedCommentstxt.save,
			tooltip: '',  width: '90%', submitdata: {action:'ThreadedComments_inline_comment_save', _inline_edit: nonce} } );
		$('a.comment-edit-link').click(function() {
			$(this).parents('h4').nextAll('div.comment-edit').trigger("edit");
			return false;
		});
	}
	
	$('#cancel-comment-reply-link').click(function() {
		$('#comment').val('');
		$('#comment_parent').val('');
		if (!isSingle ) $("#respond").hide();
		$(this).parents("li").removeClass('replying');
		$(this).parents('#respond').prev("li").removeClass('replying');
		$("#respond").removeClass('replying');
	});
	
	$('a.comment-reply-link,a[href=#respond]').live('click', function() {
			$('#comments li').removeClass('replying');
			$(this).parents("li").eq(0).addClass('replying');
			$("#respond").addClass('replying').show();
			$("#comment").focus();
		});

  $("li[id^='comment'] > div.commentcontent, li[id^='ThreadedComments'] > h4, li[id^='comment'] > h4").live('hover',
  function() {
      $(this).parents("li").eq(0).addClass('selected');
    }, function() {
      $(this).parents("li").eq(0).removeClass('selected');
  });
				
	function removeYellow() {
    var commentBGColor = commentEvenRowColor;

		$('li.newcomment:not(.animating), tr.newcomment:not(.animating)').each(function() {

      var prevLi = $(this).next("il.comment");
      if(!prevLi.length){
        prevLi = $(this).next("il.comment");
      }
      if(!prevLi.length){
        prevLi = $(this).prev("li.comment");
      }
      if(!prevLi.length){
        prevLi = $(this).parent("li.comment");
      }
      //      console.log(prevLi);
      if(prevLi.hasClass("even")){
        //        console.log(commentBGColor);
        commentBGColor = commentOddRowColor;
      }

//      console.log("Yellow:" + commentBGColor);

			if (isElementVisible(this)) {
        $(this).toggleClass("odd", commentBGColor == commentOddRowColor);
        $(this).toggleClass("even", commentBGColor == commentEvenRowColor);
        
        $(this).stop();
//        console.log(commentBGColor);
				$(this).children("div.colored-div").animate({backgroundColor:commentBGColor}, commentBGColorTime, function(){
					$(this).parent("li").removeClass('newcomment');
          $(this).attr("style", "background-color:"+commentBGColor+";");
				});
			}
		});

		if (isFirstFrontPage) {
			$('#comments > li.newupdates:not(.animating)').each(function() {
        var prevLi = $(this).next("il.comment");
        if(!prevLi.length){
          prevLi = $(this).next("il.comment");
        }
        if(!prevLi.length){
          prevLi = $(this).prev("li.comment");
        }
        if(!prevLi.length){
          prevLi = $(this).parent("li.comment");
        }
        //      console.log(prevLi);
        if(prevLi.hasClass("even")){
          //        console.log(commentBGColor);
          commentBGColor = commentOddRowColor;
        }

				if (isElementVisible(this)) {
          $(this).toggleClass("odd", commentBGColor == commentOddRowColor);
          $(this).toggleClass("even", commentBGColor == commentEvenRowColor);
          $(this).stop();
//          console.log(commentBGColor);
					$(this).children("div.colored-div").animate({backgroundColor:commentBGColor}, commentBGColorTime, function(){
              $(this).parent("li").removeClass('newupdates');
              $(this).attr("style", "background-color:"+commentBGColor+";");
          });
        }
			});
		}
		titleCount();
	}

	// Activate keyboard navigation
	if (!isSingle)	{
		document.onkeydown = function(e) {
			e = e || window.event;
			if (e.target)
				element = e.target;
			else if (e.srcElement)
				element = e.srcElement;
			
			if( element.nodeType == 3)
				element = element.parentNode;
				
			if( e.ctrlKey == true || e.altKey == true || e.metaKey == true )
				return;
			
			var keyCode = (e.keyCode) ? e.keyCode : e.which;

			if (keyCode && (keyCode != 27 && (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') ) )
				return;
				
			switch(keyCode) {
				
				// "r" key
				case 82:
					if (!commentLoop) {
						$(postsOnPage[currPost]).removeClass('keyselected').children('h4').trigger('mouseleave');
						$(postsOnPage[currPost]).find('a.comment-reply-link:first').click();
					} else {
						$('#'+commentsOnPost[currComment]).removeClass('keyselected').children('h4').trigger('mouseleave');
						$('#'+commentsOnPost[currComment]).find('a.comment-reply-link').click();
					}
					removeYellow();
					if (e.preventDefault)
						e.preventDefault();
					else
						e.returnValue = false;
					break;
				
				// "o" key
				case 79:
					$("#togglecomments").click();
					if (typeof postsOnPage[currPost] != "undefined") {
						if (!isElementVisible(postsOnPage[currPost])) {
							$.scrollTo(postsOnPage[currPost], 150);
						}
					}
					break;
					// "t" key
				case 84:
					$.scrollTo(0, 150);
					break;
				// "esc" key
				case 27:
					if (element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') {
						$('#cancel-comment-reply-link').click();
						$(element).blur();
					}
					else {
						$('#'+commentsOnPost[currComment]).each(function(e) {
							$(this).removeClass('keyselected');
						});
						
						$(postsOnPage[currPost]).each(function(e) {
							$(this).addClass('keyselected');
						});

						commentLoop = false;
						$(postsOnPage[currPost]).each(function(e) {
							$(this).removeClass('keyselected');
						});
						currPost =- 1;
					}
						$('#help').hide();
						
					break;
				case 0,191:
					$("#help").toggle();
					if (e.preventDefault)
						e.preventDefault();
					else
						e.returnValue = false;
					break;
			}
		}
	}

	
	// Actvate autgrow on textareas
	if (isFrontPage) {
		$('#posttext, #comment').keypress(function(e) {autgrow(this, 3);});
		$('#posttext, #comment').focus(function(e) {autgrow(this, 3);});
	}
	
	// Catch new comment submit
	if (isUserLoggedIn && !isPage)
		$("#commentform").submit(function(trigger) {
			newComment(trigger);
			trigger.preventDefault();
			$(this).parents("li").removeClass('replying');
			$(this).parents('#respond').prev("li").removeClass('replying');
		});
	
	// Hide error messages on load
	$('#posttext_error, #commenttext_error').hide();
	

 	// Check if new comments or updates appear on scroll and fade out
	$(window).scroll(function() { removeYellow(); });

  $('#comment').val('');
	$('#comment_parent').val('');
});