   var tinymceCurrentCommentId;
   var initedComments = new Array();

   var InsertLink;
   
	function monitorTextareaForSelection(textArea) {
	    var selText = '';

        if (document.selection) { //IE
        	selText = document.selection.createRange().text;
        } else if (textArea.selectionStart || textArea.selectionStart == 0){ //FF
        	selText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);
        }

        if (selText.length > 0) {
            $$('a[id^="'+textArea.id+'-btn"]').each(function(d) {
                d.addClassName('linkButtonEnabled');
                d.removeClassName('linkButtonDisabled');
            });
        } else {
            $$('a[id^="'+textArea.id+'-btn"]').each(function(d) {
                d.removeClassName('linkButtonEnabled');
                d.addClassName('linkButtonDisabled');
            });
        }
	}

	function popupAddLink(textArea) {
		if (InsertLink!=null) InsertLink.close(); InsertLink=null;

		var width = 325;
	    var height = 200;
	    var options = 'status=yes,';

		var leftPos = (screen.availWidth - width) / 2;
        var topPos = (screen.availHeight - height) / 2;
        options += 'width=' + width + ',height=' + height + ',left=' + leftPos + ',top=' + topPos;

	    InsertLink = window.open('popupAddLink.action?parentTextAreaId='+textArea.id, 'InsertLink', options);
	}

	function doAddLink(textAreaId, url, target, title) {
        var textArea = $(textAreaId);

        if (textArea) {
        	if( document.selection ){ // IE
        		// The current selection
        		var range = document.selection.createRange();
        		// We'll use this as a 'dummy'
        		var stored_range = range.duplicate();
        		// Select all text
        		stored_range.moveToElementText( textArea );
        		// Now move 'dummy' end point to end point of original range
        		stored_range.setEndPoint( 'EndToEnd', range );
        		// Now we can calculate start and end points
        		textArea.selectedText = range.text;
        		textArea.selectionStart = stored_range.text.length - range.text.length;
        		textArea.selectionEnd = textArea.selectionStart + range.text.length;
  	          	if (textArea.selectionStart < 0) {
 	              textArea.selectionStart = 0;
 	              textArea.selectionEnd = 0;
  	          	}
	        } else if (textArea.selectionStart || textArea.selectionStart == 0){ //FF
	           textArea.selectedText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);
	        }

	        var len = textArea.value.length;
	        var start = textArea.selectionStart;
	        var end = textArea.selectionEnd;
	        var sel = textArea.value.substring(start, end);

	        if (sel.length > 0) {
		        if (target != '') {
		            target = ' target="'+target+'"';
		        }

		        if (title != '') {
		        	title = ' title="'+title+'"';
		        }
		        var replace = '<a href="'+url+'"'+title+target+'>' + sel + '</a>';

		        textArea.value =  textArea.value.substring(0,start) + replace + textArea.value.substring(end,len);
	        }

	        monitorTextareaForSelection(textArea);
        }
	}

	function doFormatCommand(textAreaId, command) {
		var textArea = $(textAreaId);

        if (textArea) {
        	if( document.selection ){ // IE
        		// The current selection
        		var range = document.selection.createRange();
        		// We'll use this as a 'dummy'
        		var stored_range = range.duplicate();
        		// Select all text
        		stored_range.moveToElementText( textArea );
        		// Now move 'dummy' end point to end point of original range
        		stored_range.setEndPoint( 'EndToEnd', range );
        		// Now we can calculate start and end points
        		textArea.selectedText = range.text;
        		textArea.selectionStart = stored_range.text.length - range.text.length;
        		textArea.selectionEnd = textArea.selectionStart + range.text.length;
  	          	if (textArea.selectionStart < 0) {
 	              textArea.selectionStart = 0;
 	              textArea.selectionEnd = 0;
  	          	}
            } else if (textArea.selectionStart || textArea.selectionStart == 0){ //FF
               textArea.selectedText = textArea.value.substring(textArea.selectionStart,textArea.selectionEnd);
            }

            var len = textArea.value.length;
            var start = textArea.selectionStart;
            var end = textArea.selectionEnd;
            var sel = textArea.value.substring(start, end);

            if (sel.length > 0) {
                var replace = sel;
                if (command == 'bold') {
                	replace = '<strong>' + sel + '</strong>';
                } else if (command == 'italic') {
                	replace = '<em>' + sel + '</em>';
                } else if (command == 'underline') {
                	replace = '<u>' + sel + '</u>';
                }

                textArea.value =  textArea.value.substring(0,start) + replace + textArea.value.substring(end,len);

                monitorTextareaForSelection(textArea);
            }
        }
	}
	
    function resetAllCommentableAreas() {
        //closes all comment boxes and displays links
        $$('div[id^="commentLink"]').each(function(d) {
            d.style.display='';
        });
        $$('div[id^="addComment"]').each(function(d) {
            tinyMCE.execCommand('mceRemoveControl', false, d.id);
        });
        $$('div[id^="commentBox"]').each(function(d) {
            d.style.display='none';
        });
        $$('div[id^="commentErrors-"]').each(function(d) {
            d.style.display='none';
        });
        $$('div[id^="emptyPingError-"]').each(function(d) {
            d.hide();
        });
        $$('div[id^="pingLimitError-"]').each(function(d) {
            d.hide();
        });
    }

    function tinymceCommentFinished() {
        if (initedComments.indexOf(tinymceCurrentCommentId) >= 0) {
        } else {
            initedComments.push(tinymceCurrentCommentId);
        }

        var commentBoxObj = $("commentBox-" + tinymceCurrentCommentId);
        var commentLoadingObj = $("commentLoading-" + tinymceCurrentCommentId);

        commentBoxObj.style.display = '';
        commentLoadingObj.style.display = 'none';
    }

    function loadSubCommentArea(commentId) {
        //resetAllCommentableAreas();

        tinymceCurrentCommentId = commentId;
        var tmceObjId = "addComment-" + commentId;
        var commentLinkObj = $("commentLink-" + commentId);
        var commentLoadingObj = $("commentLoading-" + commentId);
        var commentBoxObj = $("commentBox-" + tinymceCurrentCommentId);

        commentBoxObj.style.display = '';
        commentLinkObj.style.display = 'none';
        //commentLoadingObj.style.display = '';

    }

    function loadTinyMCE(commentId) {
        //resetAllCommentableAreas();

        tinymceCurrentCommentId = commentId;
        var tmceObjId = "addComment-" + commentId;
        var commentLinkObj = $("commentLink-" + commentId);
        var commentLoadingObj = $("commentLoading-" + commentId);

        commentLinkObj.style.display = 'none';
        commentLoadingObj.style.display = '';

        if (initedComments.indexOf(tinymceCurrentCommentId) < 0) {
	        var strButtons1 = 'link,unlink,code';
	        var strPlugins  = 'paste,media,safari';
	        var pasteOptions1 = false;
	        var pasteOptions2 = false;
	        var pasteOptions3 = false;
        	var br=getBrowser();
	        if (br[0] == 'msie') {
	            pasteOptions3 = true;
	        }
	        var bResize     = false;
	        var oninitFunc  = 'tinymceCommentFinished';

	          tinyMCE.init({
	            theme : "advanced",
	            skin : "comment",
	            mode : "exact",
	            oninit : oninitFunc,
	            elements : tmceObjId,
	            theme_advanced_toolbar_location : "bottom",
	            theme_advanced_toolbar_align : "right",
	            theme_advanced_resize_horizontal : false,
	            theme_advanced_resizing : bResize,
	            apply_source_formatting : true,
	            theme_advanced_statusbar_location : "none",
	            theme_advanced_path : false,
	            plugins : strPlugins,
	            paste_remove_spans : pasteOptions1,
	            paste_remove_styles : pasteOptions2,
	            paste_auto_cleanup_on_paste : pasteOptions3,
	            save_callback : "convertWord",
	            theme_advanced_buttons1 : strButtons1,
	            theme_advanced_buttons2 : "",
	            theme_advanced_buttons3 : "",
	            content_css : "/css/editor_content_andre.css",
	            gecko_spellcheck : true,
	            convert_newlines_to_brs : false,
	            remove_linebreaks : true,
	            entity_encoding : "raw",
	            media_strict : false,
	            convert_urls : false,
	            extended_valid_elements  : "script[charset|defer|language|src|type|badgetype]"
	          });

	          tinyMCE.execCommand('mceAddControl', false, tmceObjId);

        } else {
            tinymceCommentFinished();
        }
    }

    function mainTinymceFinished() {
        var commentBoxObj = $("mainCommentBox");
        var commentLoadingObj = $("mainCommentLoading");

        commentBoxObj.style.display = '';
        commentLoadingObj.style.display = 'none';
    }

   function loadTinyMCEforMain() {
        //var commentLoadingObj = $("mainCommentLoading");
        //commentLoadingObj.style.display = '';

        var strButtons1 = 'link,unlink,code';
        var strPlugins  = 'paste,media,safari';
        var pasteOptions1 = false;
        var pasteOptions2 = false;
        var pasteOptions3 = false;
        var bResize     = false;
    	var br=getBrowser();
        if (br[0] == 'msie') {
            pasteOptions3 = true;
        }

        var oninitFunc  = 'mainTinymceFinished';

          tinyMCE.init({
            theme : "advanced",
            skin : "comment",
            mode : "exact",
            oninit : oninitFunc,
            elements : 'addMainComment',
            theme_advanced_toolbar_location : "bottom",
            theme_advanced_toolbar_align : "right",
            theme_advanced_resize_horizontal : false,
            theme_advanced_resizing : bResize,
            apply_source_formatting : true,
            theme_advanced_statusbar_location : "none",
            theme_advanced_path : false,
            plugins : strPlugins,
            paste_remove_spans : pasteOptions1,
            paste_remove_styles : pasteOptions2,
            paste_auto_cleanup_on_paste : pasteOptions3,
            save_callback : "convertWord",
            theme_advanced_buttons1 : strButtons1,
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            content_css : "/css/editor_content_andre.css",
            gecko_spellcheck : true,
            convert_newlines_to_brs : false,
            remove_linebreaks : true,
            entity_encoding : "raw",
            media_strict : false,
            convert_urls : false,
            extended_valid_elements  : "script[charset|defer|language|src|type|badgetype]"
          });
    }

    function grpPingTinymceFinished() {
        var commentBoxObj = $("mainPingBody");
        var commentLoadingObj = $("mainPingLoading");

        commentBoxObj.style.display = '';
        commentLoadingObj.style.display = 'none';
    }

   function loadTinyMCEforGrpPing() {
        //var commentLoadingObj = $("mainCommentLoading");
        //commentLoadingObj.style.display = '';

        var strButtons1 = 'link,unlink,code';
        var strPlugins  = 'paste,media,safari';
        var pasteOptions1 = false;
        var pasteOptions2 = false;
        var pasteOptions3 = false;
        var bResize     = false;
    	var br=getBrowser();
        if (br[0] == 'msie') {
            pasteOptions3 = true;
        }

        var oninitFunc  = 'grpPingTinymceFinished';

          tinyMCE.init({
            theme : "advanced",
            skin : "ping",
            mode : "exact",
            oninit : oninitFunc,
            elements : 'pingBody',
            theme_advanced_toolbar_location : "bottom",
            theme_advanced_toolbar_align : "right",
            theme_advanced_resize_horizontal : false,
            theme_advanced_resizing : bResize,
            apply_source_formatting : true,
            theme_advanced_statusbar_location : "none",
            theme_advanced_path : false,
            plugins : strPlugins,
            paste_remove_spans : pasteOptions1,
            paste_remove_styles : pasteOptions2,
            paste_auto_cleanup_on_paste : pasteOptions3,
            save_callback : "convertWord",
            theme_advanced_buttons1 : strButtons1,
            theme_advanced_buttons2 : "",
            theme_advanced_buttons3 : "",
            content_css : "/css/editor_content_andre.css",
            gecko_spellcheck : true,
            convert_newlines_to_brs : false,
            remove_linebreaks : true,
            entity_encoding : "raw",
            media_strict : false,
            convert_urls : false,
            extended_valid_elements  : "script[charset|defer|language|src|type|badgetype]"
          });

    }

   /* RAM - 12/10/08
   Pasting from Word on Windows into Firefox results in css being added in an html comment that
   displays in the article body. This callback method will remove those html comments when the
   Word Paste button is used.
   */
   function convertWord (type, content, body) {
     //alert(content);
     if (content.search(/mso-/) != -1) {
       content = content.replace(/<p>&lt;!(?:--[\s\S]*?--\s*)?&gt;<\/p>\s*/g,'');
       content = content.replace(/&lt;!(?:--[\s\S]*?--\s*)?&gt;\s*/g,'');
     }
     //content = content.toLowerCase(); // Some dummy logic
     //alert(content);

     return content;
   }

    /* comment functions
--------------------------------------------------------------------------------------- */

/* Preload Comment Button Images */
var commentImgPost    = new Image(); commentImgPost.src    = 'images/buttons/btn_post.png';
var commentImgPosting = new Image(); commentImgPosting.src = 'images/buttons/btn_posting.png';



function postThreadedComment(id,replyToThreadCommentId,meId,cType, contentOwnerId,commentId, twitterCheckbox, facebookCheckbox, canBeShared){
  var body = '';
  
  //Hide all error messages
  if ($('commentErrors')) {
    $('commentErrors').hide();
  }

  if(commentId){
  	if($('commentBtnPost-' + commentId)) { $('commentBtnPost-' + commentId).blur(); }
  	body = $F('addComment-' + commentId);
  }else{
  	if($('mainCommentBtnPost')) { $('mainCommentBtnPost').blur(); }
  	body = $F('addMainComment');
  }
 
    var sendTweet = false;
    if($(twitterCheckbox) != null && $(twitterCheckbox).checked) {
      sendTweet = true;
    }
    
    var sendFacebook = false;
    if($(facebookCheckbox) != null && $(facebookCheckbox).checked) {
      sendFacebook = true;
    }

	var req = gatherAjax.Request({
		url: 'postComment.action',
		options: {
			method: 'POST',
			parameters: {
				body: body,
		        contentId: id,
		        replyToThreadCommentId: replyToThreadCommentId,
		        meId: meId,
		        contentType: cType,
		        doTweet: sendTweet,
		        doFacebook: sendFacebook,
		        canBeShared: canBeShared
		      },
			onSuccess: function(transport) {
				if(transport.responseText.isJSON()){

				    responseObj = transport.responseText.evalJSON();

				    if(responseObj.success) {

					} else {
					    //show the error message in an error div if possible
					    if (commentId) {
					       if ($('commentErrors-' + commentId)) {
	                           $('commentErrors-' + commentId).innerHTML = responseObj.message;
	                           $('commentErrors-' + commentId).show();
	                        } else {
	                           alert(responseObj.message);
	                        }
					    } else {
						    if ($('commentErrors')) {
						       $('commentErrors').innerHTML = responseObj.message;
						       $('commentErrors').show();
						    } else {
						       alert(responseObj.message);
						    }
                        }

	                    if(!commentId){
	                        if($('mainCommentBtnPost')) {
	                          $('mainCommentSubmitting').hide();
	                          $('mainCommentBtnPost').show();
	                        }
	                    } else {
                            if($('commentBtnPost-' + commentId)) {
                              $('commentSubmitting-' + commentId).hide();
                              $('commentBtnPost-' + commentId).show();
                            }
	                    }
	               }

				}else{
					//the action executed successfully, and the response should be the result of the view comments action

					$('comments').innerHTML = transport.responseText;

					if(!commentId){
						$('addMainComment').value = '';
						//setTimeout(function() { tinyMCE.get('addMainComment').setContent('');}, 500);

				        if($('mainCommentBtnPost')) {
				          $('mainCommentSubmitting').hide();
				          $('mainCommentBtnPost').show();
				        }
					}
				}

     		},
     		onError: function(transport){
     		}
     	}
	});
	
	// reset the checkbox to 'unchecked'
	if($(twitterCheckbox) != null) {
	  $(twitterCheckbox).checked=false;
	}
	$(facebookCheckbox).checked=false;
}

function removeCommentThread(form){

	var elId = 'commentThread-' + form.commentId.value;
	var el = parent.document.getElementById(elId);

	if(typeof Effect != 'undefined') {
		new parent.Effect.DropOut(el);
	} else {
		el.hide();
	}

	gatherAjax.Request({
		url: form.action,
		options: {
    		method: 'POST',
    		parameters: form.serialize(true),
      		onSuccess: function(transport) {

		        if(transport.responseText.isJSON()){

		        	var response = transport.responseText.evalJSON();

		        	if(response.success) {
		                //never happens, success returns non-json (replacement jsp for comments)
			        }else{
			        	//error!
			        }

		        } else {

					parent.myLightWindow.deactivate();
					parent.document.getElementById('comments').innerHTML = transport.responseText;

		        }

      		},
      		onError: function(transport){parent.myLightWindow.deactivate();}
   		}
	});
}

var comMesg = [ 'Comment action failed. Please try again later.' ];

function commentAction(act,id,el,dropAccept,meId,contentType) {
  if($(el)) {

    if(act == 'delete' || act == 'remove' || act == 'deny') {
      if(typeof Effect != 'undefined') {
        new Effect.DropOut(el);
        if ($('commentExtended-' + id)) {
            new Effect.DropOut('commentExtended-' + id);
        }
      } else {
        $(el).hide();
        if ($('commentExtended-' + id)) {
            $('commentExtended-' + id).hide();
        }
      }
    } else if(act == 'accept') {
      if(dropAccept) { // Pending Comments page requires both states remove the comment from the list
        if(typeof Effect != 'undefined') {
            new Effect.DropOut(el);
	        if ($('commentExtended-' + id)) {
	            new Effect.DropOut('commentExtended-' + id);
	        }
        } else {
            $(el).hide();
	        if ($('commentExtended-' + id)) {
	            $('commentExtended-' + id).hide();
	        }
        }
      } else {
        var removeLink = "<a href=\"#\" onclick=\"commentAction('remove',"+id+",'comment-"+id+"');return false;\" class=\"lt_gray\">remove<br>comment</a>";
        $(el).removeClassName('commentPending');
        $('commentTooltip-'+id).hide();
        $('commentControls-'+id).update(removeLink);
      }
    } else {
      alert(comMesg[0]);
      return false;
    }

    var req = gatherAjax.Request({
		url: 'commentStatus.action',
		options: {
			method: 'POST',
			parameters: {
				commentId: id,
                action: act,
                meId: meId
		      },
			onSuccess: function(transport) {

				if(transport.responseText.isJSON()){

				    responseObj = transport.responseText.evalJSON();

				    if(responseObj.success) {

						//if(act == 'delete' || act == 'remove' || act == 'deny') { $(el).remove(); }

					} else {

				    	$(el).show();
				    	alert(responseObj.message);
	               }

				}else{

					//the action executed successfully, and the response should be the result of the view comments action

					$('comments').innerHTML = transport.responseText;
				}

     		},
     		onError: function(transport){
     		}
     	}
	});

  }
};