/*-------------------------[ comments ]------------------------------*/
cghub.comments = {
    'canEditComments': false,
    'canDeleteComments': false,
	'canAddComments': true
};



cghub.comments.onCommentsLoaded = function() {
	//signatures
	var showSignCookie = readCookie('comments_showSignatures');
	if (showSignCookie !== null && parseInt(showSignCookie) == 0) {
		$('.comment_signature').hide();
	} else {
		$('.comment_signature').show();
	}



	if (typeof onReadyUserpicTooltipInUse != 'undefined' && !onReadyUserpicTooltipInUse) {
		onReadyUserpicTooltipInUse = true;
		setTimeout("onReadyUserpicTooltip();onReadyUserpicTooltipInUse = false;", 2000);
	}
    

	cghub.comments.canAddComments = cghub.comments.canAddComments && cghub.user.id !== null && cghub.user.id !== 0;

    //reply, edit, report abuse and delete links

	$('#comments a[rel^="reply"]').each(function(){
		if (cghub.comments.canAddComments) {
			$(this).removeClass('hidden');
			return true; //continue
		}
	});

	$('#comments a[rel^="edit_"]').each(function(){
		if (cghub.comments.canEditComments && cghub.comments.canAddComments) {
			$(this).removeClass('hidden');
			return true; //continue
		}

		var commenterId = $(this).attr('rel').split('_')[1];
		if (commenterId == cghub.user.id) {
			$(this).removeClass('hidden');
			return true; //continue
		}
	});

	$('#comments a[rel^="delete_"]').each(function(){
		if (cghub.comments.canDeleteComments) {
			$(this).removeClass('hidden');
			return true; //continue
		}

		var commenterId = $(this).attr('rel').split('_')[1];
		if (commenterId == cghub.user.id) {
			$(this).removeClass('hidden');
			return true; //continue
		}

		$(this).click(function(){
			if (!confirm('Delete comment?')) {
				return false;
			}
			var commentId = $(this).attr('id').split('_')[2];
			var parentCommentId = cghub.comments.getParentCommentId(commentId);

			var url = $(this).attr('href');

			return false;
		});
	});

	if (cghub.user.id) {
		$('#comments a[rev="report"]').removeClass('hidden');
	}

	$('#comments h4.date[rel]').each(function(){
		var d, relTime;
		
		d = new Date($(this).attr('rel'));
		relTime = d.toRelativeTime();
		$(this).html(relTime).removeAttr('rel');
	});


	/**
	 * add ajax form
	 */
	var forms = $('.add_comment_form');
	forms.each(function(){
		if (!cghub.comments.canAddComments) {
			$(this).hide();
			return true; //continue
		} else {
			cghub.comments.bindAjaxForm($(this));	
		}
	});

};


cghub.comments.bindAjaxForm = function(form, callbackOnCommentAdded) {
    var url = $.trim(form.attr('action'));

    var urlParams = cghub.url.removeParams(url).substr(1).split('/');//['comments','add or edit',model,parentId,parentCommentId]

	//console.info(urlParams);

    if (typeof urlParams[4] != 'undefined' && urlParams[4] != '') {
        var parentCommentId = urlParams[4];
    } else {
	    var parentCommentId = cghub.url.getNamedParam(url, 'parentCommentId');
        parentCommentId = parentCommentId ? parentCommentId : 0;
    }

    url = cghub.url.addGetParam(url, 'call', 'ajax');
    url = cghub.url.addGetParam(url, '_', Math.random());
    form.ajaxForm({
          'url': url,
	      //escaping international characters
		  'beforeSubmit': function(postData, form, options) {
			  for (var key in postData) {
				  if (postData[key].name == 'data[Comment][text]') {
				      postData[key].value = cghub.ajax.escapePostValue(postData[key].value);
				  }
			  }
		  },
          'success': function(data, status, xhr) {
	          if (typeof data == 'object' || data.isJSON()) {
		          if (typeof data != 'object') {
			          data = $.parseJSON(data);
		          }
		          if (typeof data.result != 'undefined' && data.result == 'error') {
			          var divId = 'msg_'+Math.round(Math.random() * 100000);
			          form.append('<div id="'+divId+'" style="color:red;">'+data.message+'</div>');
			          setTimeout(function(){ $('#'+divId).hide(); }, 5000);
		          }

	          } else {
		          //console.info('replacing #comment_thread_'+parentCommentId);
				  //console.info(data);

				  $('#comment_thread_'+parentCommentId).html(data);

				  form.find('textarea').val('');

				  setTimeout(cghub.comments.onCommentsLoaded, 200);
	          }

	          if (typeof callbackOnCommentAdded != 'undefined') {
		          callbackOnCommentAdded();
	          }
          }
    });
};


$('#comments').ready(function(){
    if (cghub.comments.userAvatar != null) {
        $('#addCommentFormDiv form img[src*="1x1.gif"]').attr('src', cghub.comments.userAvatar).show();
    }

    cghub.comments.onCommentsLoaded();

	if (cghub.user.id) {
		$('#addCommentLoggedIn').show();
	} else {
		$('#addCommentNotLoggedIn').show();
	}
});


cghub.comments.del = function(link) {
	if (!confirm('Are you sure you want to delete comment?')) {
		return false;
	}

	var commentId = $(link).attr('rel').split('_')[2];
	var parentCommentId = cghub.comments.getParentCommentId(commentId);

	var url = $(link).attr('href');
	url = cghub.url.addGetParam(url, 'parentCommentId', parentCommentId);
	url = cghub.url.addGetParam(url, 'call', 'ajax');

//	console.info(commentId, parentCommentId, url);


	$.ajax({
		'type': 'GET',
		'cache': false,
		'url': url,
		'success': function(response) {
			$('#comment_thread_'+parentCommentId).html(response);

            setTimeout(cghub.comments.onCommentsLoaded, 200);
		}
	});

	return false;
};


cghub.comments.toggleTips = function(link) {
	link = $(link);
	var id = link.attr('rel');
	var currentTitle = link.attr('title');
	var newTitle = link.attr('rev');

	if ($('#'+id).is(':visible')) {
		var img = '<img src="/img/toggle/closed.gif" />';
		$('#'+id).hide();
	} else {
		var img = '<img src="/img/toggle/open.gif" />';
		$('#'+id).show();
	}

	link.html(img+' '+newTitle).attr('title', newTitle).attr('rev', currentTitle);


	return false;
};



cghub.comments.getParentCommentId = function(commentId) {
	//console.info(commentId, $('#comment_'+commentId), $('#comment_'+commentId).parents('li[id^="comment_thread_"], div[id^="comment_thread_"]'));
	return $('#comment_'+commentId).parents('li[id^="comment_thread_"], div[id^="comment_thread_"]').attr('id').split('_')[2];
};


cghub.comments.addReplyForm = function (link) {
	var attrs = $(link).attr('id').split('_');
	var model = attrs[1];
	var parentId = attrs[2];
	var parentCommentId = attrs[3];

	//$('div.preview').remove();

	var formHtml = $('#addCommentFormDiv').html();
	var action = '/comments/add/'+model+'/'+parentId+'/'+parentCommentId;
	var commentTextareaId = 'comment_textarea_'+model+'_'+parentId+'_'+parentCommentId;

	if (formHtml.indexOf('<form') != -1 || formHtml.indexOf('<FORM') != -1) {
		formHtml = '<form method="post" action="'+action+'" class="nopad"><fieldset style="display: none;"><input name="_method" value="POST" type="hidden"></fieldset><h3>Leave a new comment</h3><div class="clear"></div><textarea name="data[Comment][text]" cols="30" rows="6" style="width: 350px; margin-bottom: 5px;" id="'+commentTextareaId+'"></textarea><div><input class="btn" value="Submit" type="submit"></div></form>';
	} else if(formHtml.indexOf('to add comment') != -1) {
		alert('Please log in or sign up to add comment.');
		return false;
	} else {
		formHtml = '<h4>Please <a href="https://'+siteTopDomain+'/login/">Log in</a> or <a href="https://'+siteTopDomain+'/registration/">Sign up</a> to add comment.</h4>';
	}

	if ($('form[action="'+action+'"]').length == 0) {
		$('#comment_thread_'+parentCommentId).show();
		$('#comment_thread_'+parentCommentId).append(formHtml);

		setTimeout(function(){
			$('form[action="'+action+'"]').show();
			//cghub.comments.addWysiwygToTextarea(commentTextareaId);
			//cghub.comments.focusWysiwyg(commentTextareaId);
			$('form[action="'+action+'"] textarea').focus();

			cghub.comments.bindAjaxForm($('form[action="'+action+'"]'));

		}, 200);

	} else if($('#comment_thread_'+parentCommentId).is(':visible') && $('form[action="'+action+'"]').is(':visible'))  {
		$('form[action="'+action+'"]').hide();
	} else {
		$('#comment_thread_'+parentCommentId).show();
		$('form[action="'+action+'"]').show();

		$('form[action="'+action+'"] textarea').focus();
		//cghub.comments.focusWysiwyg(commentTextareaId);
	}

	return false;
};


cghub.comments.editCommentForm = function (link) {
	var attrs = $(link).attr('rel').split('_');

	var commenterId = attrs[1];
	var commentId = attrs[2];
	var parentCommentId = cghub.comments.getParentCommentId(commentId);

	var formHtml = $('#addCommentFormDiv').html();
	var action = '/comments/edit/'+commentId+'/parentCommentId:'+parentCommentId+'/';
	var commentTextareaId = 'comment_textarea_'+commentId;

	/**
	* @deprecated
	* @since ajax get text
	*/
	//	var commentText = $('span#commentText_'+commentId).html();
	//	commentText = commentText.replace(/<(div|DIV) class=[\"]?editedComment[\"]?>.*<\/(div|DIV)>/, '');

	/**
	* @deprecated
	* @since style in nicEdit.js
	*/
	//	var notClosingDivTag = '[^<]*[^\/]*[^d]*[^i]*[^v]*[^>]*';
	//	var re = new RegExp('<(div|DIV) class=[\"]?quote[\"]?>('+notClosingDivTag+')<\/(div|DIV)>', 'ig');
	//	commentText = commentText.replace(re, '<div class="quote" style="border:1px dotted black;">$1</div>');

	/**
	* @deprecated
	* @since removeImgOverflowDiv in controller
	*/
	//	var re2 = new RegExp('<div style="width:[^p]+px;[^o]*overflow-x:[^s]*scroll;">(<img alt="[^"]*" src="[^"]*"[^>]*>)</div>', 'ig');
	//	commentText = commentText.replace(re2, '$1');

	var editImgSrc = $(link).find('img').attr('src');
	$(link).find('img').attr('src', '/img/ajax-loader2.gif');

	$.ajax({
		'url':'/comments/getCommentTextForEdit/'+commentId+'/?call=ajax',
		'type':'GET',
		'cache':false,
		'success':function(response) {
		  var commentText = response;
		  cghub.comments.editCommentAddForm(commentText, commentTextareaId, formHtml, action, commentId);

		  $(link).find('img').attr('src', editImgSrc);
		}
	});

	return false;
};

cghub.comments.editCommentAddForm = function (commentText, commentTextareaId, formHtml, action, commentId) {
	if (formHtml.indexOf('<form') != -1 || formHtml.indexOf('<FORM') != -1) {
		formHtml = '<form method="post" action="'+action+'" class="nopad"><fieldset style="display: none;"><input name="_method" value="POST" type="hidden"></fieldset><h3>Edit comment</h3><div class="clear"></div><textarea name="data[Comment][text]" cols="30" rows="6" style="width: 350px; margin-bottom: 5px;" id="'+commentTextareaId+'">'+commentText+'</textarea><div><input class="btn" value="Submit" type="submit"></div></form>';
	} else if(formHtml.indexOf('to edit comment') != -1) {
		alert('Please log in or sign up to edit comment.');
		return false;
	} else {
		formHtml = '<h4>Please <a href="https://'+siteTopDomain+'/login/">Log in</a> or <a href="https://'+siteTopDomain+'/registration/">Sign up</a> to edit comment.</h4>';
	}

	var commentLink = $('#comments a[rel^="edit_"][rel$="_'+commentId+'"]');

	if ($('form[action="'+action+'"]').length == 0) {
		//$('#comment_thread_'+parentCommentId).show();
		//$('#comment_thread_'+parentCommentId).append(formHtml);

		commentLink.parents('li.comment').append(formHtml);

		setTimeout(function(){
			$('form[action="'+action+'"]').show();
			//cghub.comments.addWysiwygToTextarea(commentTextareaId);
			//cghub.comments.focusWysiwyg(commentTextareaId);
			$('form[action="'+action+'"] textarea').focus();

			cghub.comments.bindAjaxForm($('form[action="'+action+'"]'));
		}, 200);

		setTimeout("onReadyTooltipSpan()", 500);
	} else if($('form[action="'+action+'"]').is(':visible'))  {
		$('form[action="'+action+'"]').hide();
	} else {
		//$('#comment_thread_'+parentCommentId).show();
		$('form[action="'+action+'"]').show();

		//cghub.comments.focusWysiwyg(commentTextareaId);
		$('form[action="'+action+'"] textarea').focus();
	}
};


cghub.comments.commentExpandCollapse = function (link) {
	var attrs = $(link).attr('id').split('_');
	var model = attrs[1];
	var parentId = attrs[2];
	var parentCommentId = attrs[3];
	var canDeleteComments = attrs[4];
	//	var divClass = $('#comment_'+parentCommentId).attr('class');

	if ($('#comment_thread_'+parentCommentId).is(':visible')) {
		cghub.comments.commentCollapseThread(model, parentId, parentCommentId, canDeleteComments);
	} else {
		cghub.comments.commentExpandThread(model, parentId, parentCommentId, canDeleteComments);
	}
};

cghub.comments.commentExpandThread = function (model, parentId, parentCommentId, canDeleteComments) {
  var link = $('#expandLink_'+model+'_'+parentId+'_'+parentCommentId+'_'+canDeleteComments);
  var thread = $('#comment_thread_'+parentCommentId).html();

  if ($.browser.msie) {
    var loaded = thread.toLowerCase().trim() != '<div class=clear></div>';
  } else {
    var loaded = thread.indexOf('div id="comment_') != -1;
  }



  if (loaded) {
    $('#comment_thread_'+parentCommentId).show();
    $(link).find('img').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
    $(link).removeClass('closed').addClass('opened');
  } else {

    /**
     * @deprecated
     * @since always loaded
     */
    /*
    $(link).find('img').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
    $(link).removeClass('closed').addClass('opened');

    var repliesCount = $(link).find('span.replies_count').html().trim();
    var re = /([0-9]+)/;
    repliesCount = re.exec(repliesCount)[1];


    if (repliesCount == 0) {
      return;
    }

    var repliesImg = $(link).find('img.reply_toggle');
    var loaderDiv = $(link).find('div.openl');

    //ajax working
    //is(':visible') has strange error on IE
    if (loaderDiv.hasClass('visible')) {
      return;
    }

    repliesImg.hide();
    loaderDiv.addClass('visible').show();

    $.ajax({
      'type':'GET',
      'url':'/comments/expand/'+model+'/'+parentId+'/'+parentCommentId+'/1/'+canDeleteComments+'?call=ajax',
      'cache':false,
      'success': function(response) {
        repliesImg.show();
        loaderDiv.addClass('visible').hide();

        if (response == 'empty') {
          return;
        }

        $('#comment_thread_'+parentCommentId).prepend(response);
        $('#comment_thread_'+parentCommentId).show();

        if (!onReadyUserpicTooltipInUse) {
          onReadyUserpicTooltipInUse = true;
          setTimeout("onReadyUserpicTooltip();onReadyUserpicTooltipInUse = false;", 5000);
        }

        setTimeout(cghub.comments.onCommentsLoaded, 500);
      }
    });
    */
  }

//	$(link).unbind('click');
//	$(link).bind('click', function() {
//		cghub.comments.commentCollapseThread(link);return false;
//	});

};

cghub.comments.commentCollapseThread = function (model, parentId, parentCommentId, canDeleteComments) {
  var link = $('#expandLink_'+model+'_'+parentId+'_'+parentCommentId+'_'+canDeleteComments);
  $(link).removeClass('opened').addClass('closed');

  $('#comment_thread_'+parentCommentId).hide();
  $('#comment_'+parentCommentId+' .reply_toggle').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('open', 'closed'));

//	$(link).unbind('click');
//	$(link).bind('click', function() {
//		commentExpandThread(link);return false;
//	});
}

cghub.comments.getCommentPage = function (link) {
  var attrs = $(link).attr('id').split('_');
  var model = attrs[1];
  var parentId = attrs[2];
  var parentCommentId = attrs[3];
  var page = attrs[4];

  $.ajax({
      'type': 'GET',
      'cache': false,
      'url': '/comments/expand/'+model+'/'+parentId+'/'+parentCommentId+'/'+page+'/?call=ajax',
      'success': function(response){
          //console.log(response);

        $('#getCommentPageDiv_'+model+'_'+parentId+'_'+parentCommentId+'_'+page).replaceWith(response);

        setTimeout(cghub.comments.onCommentsLoaded, 500);
    }
  });
};



/*-------------------------------------------------[ wysiwyg ]--------------------------------------*/
var wysiwygEditors = new Array();
var wysiwygFramesIds = new Array();





cghub.comments.addWysiwygToTextarea = function(textareaId) {
  if ($.browser.mobile) {
      return false;
  }
  wysiwygEditors[textareaId] = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','link','unlink','forecolor',/*'ol','ul','subscript','superscript','indent','outdent'*/,'quote','image','smile','removeformat']}).panelInstance(textareaId);
  wysiwygFramesIds[textareaId] = (window.frames.length - 1);
};


cghub.comments.focusWysiwyg = function (textareaId) {
  if (typeof window.frames[wysiwygFramesIds[textareaId]] != "undefined") {
    window.frames[wysiwygFramesIds[textareaId]].focus();
  } else if (typeof window.frames[textareaId] != "undefined") {
    window.frames[textareaId].focus();
  } else {
    $('iframe[name="'+textareaId+'"]').focus();
  }
};



/**
 *@see /views/images/list_stream.ctp
 */
cghub.comments.loadCommentForm = function (imageId, link) {


  var containerDiv = $(link).parent().find('div.qbox');
  var formDiv = containerDiv.find('div.row.comments');
  //var ratesDiv = containerDiv.find('div.row.rates');

  if (containerDiv.is(':visible')) {
    containerDiv.hide();
    return false;
  } else if (formDiv.html().length > 6) {
    containerDiv.show();
    setTimeout(function(){
      try {
        //cghub.comments.focusWysiwyg( containerDiv.html().match(new RegExp('"(comment_textarea_[^"]+)"'))[1] );
        $('#'+containerDiv.html().match(new RegExp('"(comment_textarea_[^"]+)"'))[1]).focus();
      } catch (e) {
        //pass
      }
    }, 100);
    return false;
  }

  //clear "quick comment" forms
  $('.qbox .row.comments').html('');
	
  $.ajax({
    'type': 'GET',
    'url': '/comments/addForm/Image/'+imageId+'/redirectToAnchor:image_'+imageId+'/?call=ajax',
    'cache': true,
    'success': function(response) {
      formDiv.html(response);
      containerDiv.show();
      setTimeout(function(){
        try {
          //cghub.comments.focusWysiwyg( response.match(new RegExp('"(comment_textarea_[^"]+)"'))[1] );
	      $('#'+containerDiv.html().match(new RegExp('"(comment_textarea_[^"]+)"'))[1]).focus();
        } catch (e) {
          //pass
        }

	    if (cghub.user.id) {
			$('#addCommentLoggedIn').show();

		    /**
			 * add ajax form
			 */
			var forms = $('.add_comment_form');
			forms.each(function(){
				cghub.comments.bindAjaxForm($(this), function(){
					//callback on comment added

					alert('Comment added.');

					//clear "quick comment" forms
			        $('.qbox .row.comments').html('');
				});
			});

		} else {
			$('#addCommentNotLoggedIn').show();
		}

      }, 100);
    }
  });

  /*
  $.ajax({
    'type': 'GET',
    'url': '/rates/rateElement/Image/'+imageId+'/?call=ajax',
    'cache': false,
    'success': function(response) {
      ratesDiv.html(response);
    }
  });
  */

  return false;
};

cghub.comments.getBbCodeTemplateByTag = function(bbTag) {

};

cghub.comments.modifySelection = function(link, bbTag) {
	var textarea = $(link).parents('form').find('textarea')[0];
	var href = ''; //for [url]

	if (bbTag == 'url') {
		href = prompt('Please enter url:');
		if (!href) {
			return false;
		}
		var template = '[url={HREF}]{SELECTION}[/url]';
	} else {
		var template = '[{BBTAG}]{SELECTION}[/{BBTAG}]';
	}

	if (typeof textarea.selectionStart == 'undefined') {    // Internet Explorer
		// create a range from the current selection
		var textRange = document.selection.createRange();
		// check whether the selection is within the textarea
		var rangeParent = textRange.parentElement();
		if (rangeParent === textarea) {
			var selection = textRange.text;
			var regBbTag = new RegExp('{BBTAG}', 'g');
			textRange.text = template.replace(regBbTag, bbTag).replace('{SELECTION}', selection).replace('{HREF}', href);
			//console.info(textRange.text);
		}
	} else {
		// check whether some text is selected in the textarea
		if (textarea.selectionStart != textarea.selectionEnd && bbTag == 'img') {
			href = prompt('Please enter image url:');
			if (!href) {
				return false;
			}
		}
		var before = textarea.value.substring(0, textarea.selectionStart);
		var selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
		var after = textarea.value.substring(textarea.selectionEnd);
		var regBbTag = new RegExp('{BBTAG}', 'g');
		var newText = before + template.replace(regBbTag, bbTag).replace('{SELECTION}', selection).replace('{HREF}', href) + after;
		//console.info(newText);
		textarea.value = newText;
	}

	return false;
}

cghub.comments.addToTextarea = function(link, insertText) {
	var textarea = $(link).parents('form').find('textarea')[0];

	if (typeof textarea.selectionStart == 'undefined') {    // Internet Explorer
		// create a range from the current selection
		var textRange = document.selection.createRange();
		// check whether the selection is within the textarea
		var rangeParent = textRange.parentElement();
		if (rangeParent === textarea) {
			var selection = textRange.text;
			textRange.text = selection + insertText;
		}
	} else {
		// check whether some text is selected in the textarea
		var before = textarea.value.substring(0, textarea.selectionStart);
		var selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
		var after = textarea.value.substring(textarea.selectionEnd);
		var newText = before + selection + insertText + after;
		//console.info(newText);
		textarea.value = newText;
	}

	return false;
}



/*-------------------------------------------------[ deprecated ]--------------------------------------*/


/**
 * @deprecated
 */
/*
cghub.comments.expandAllComments = function (level) {
  var attrs;
  var model;
  var parentId;
  var parentCommentId;

  if (!level) {
    level = 1;
  }

  var links = $('.expandLink.closed');

  var timeout = 0;

  if (level <= 3) {
    for (var i = 0; i < links.length; i++) {
      attrs = $(links[i]).attr('id').split('_');
      model = attrs[1];
      parentId = attrs[2];
      parentCommentId = attrs[3];
      var canDeleteComments = attrs[4];
      setTimeout("commentExpandThread('"+model+"', "+parentId+", "+parentCommentId+", "+canDeleteComments+");", timeout);
      timeout += 100;
    }
    timeout += 200;
    setTimeout("expandAllComments("+(level + 1)+")", timeout);
    timeout += 100;
  }

  if (level == 1) {
    var linkHtml = $('#expandCollapseSpan').html();
    linkHtml = linkHtml.replace(/expandAllComments/, 'collapseAllComments').replace(/expand\.gif/, 'collapse\.gif').replace(/Expand all/, 'Collapse All');
    $('#expandCollapseSpan').html(linkHtml);
  }
};
function collapseAllComments() {
  var attrs;
  var model;
  var parentId;
  var parentCommentId;
  var links = $('.expandLink.opened');
  for (var i = 0; i < links.length; i++) {
    attrs = $(links[i]).attr('id').split('_');
    model = attrs[1];
    parentId = attrs[2];
    parentCommentId = attrs[3];
    canDeleteComments = attrs[4];

    cghub.comments.commentCollapseThread(model, parentId, parentCommentId, canDeleteComments);
  }

  var linkHtml = $('#expandCollapseSpan').html();
  linkHtml = linkHtml.replace(/collapseAllComments/, 'expandAllComments').replace(/collapse\.gif/, 'expand\.gif').replace(/Collapse All/, 'Expand all');
  $('#expandCollapseSpan').html(linkHtml);
}
*/









/**
 * @deprecated
 */
/*
cghub.comments.commentPreview = function (link) {
  var formAction = $(link).parents('form').attr('action');
  formAction = formAction.substr(formAction.indexOf('/add/') + 5);
  if (formAction.charAt(formAction.length - 1) != '/') {
    formAction += '/';
  }
  var text = $(link).parent('p').siblings('textarea').val();

  $.post(
    '/comments/preview/'+formAction+'?call=ajax&rand='+Math.random(),
    {'data[Comment][text]' : text},
    function (response) {
      response = '<div class="preview"><h4>Preview:</h4>'+response+'</div>';
      $('div.preview').remove();
      $(link).parents('form').find('h3').after(response);
      //$('#CommentText1').parent('form').parent().find('a.replyLink:last')
    }
  );
//	console.log(text);
};
*/




/**
 * @deprecated
 * @since no init on focus
 */
/*
var textareasToWysiwyg = new Array();
function loadWysiwygFile() {
  var fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", 'http://'+siteTopDomain+'/js/nicEdit/nicEdit.js?_=123');
  if (typeof fileref!="undefined") {
    document.getElementsByTagName("head")[0].appendChild(fileref);
  }
}

function wysiwygReady(doNotFocus) {
  var textareaId;
  var len = textareasToWysiwyg.length
  for (i = 0; i < len; i++) {
    textareaId = textareasToWysiwyg.pop();
    wysiwygEditors[textareaId] = new nicEditor({buttonList : ['bold','italic','underline','strikethrough','link','unlink','subscript','superscript','image','smile']}).panelInstance(textareaId);
    wysiwygFramesIds[textareaId] = (window.frames.length - 1);
//		console.log(wysiwygEditors);
  }
  //for (var j in wysiwygEditors) {
  //	console.log('wysiwygEditors['+j+'] = '+wysiwygEditors[j]);
  //	console.dir(wysiwygEditors[j]);
  //}
  if (!doNotFocus) {
    if (typeof window.frames[wysiwygFramesIds[textareaId]] != "undefined") {
      window.frames[wysiwygFramesIds[textareaId]].focus();
    } else if (typeof window.frames[textareaId] != "undefined") {
      window.frames[textareaId].focus();
    } else {
      $('iframe[name="'+textareaId+'"]').focus();
    }
  }
}
function initWysiwyg(textarea) {
  var textareaId = $(textarea).attr('id');
  if (typeof textareasToWysiwyg[textareaId] != "undefined") {
    return;
  }
  textareasToWysiwyg.push(textareaId);
  if (typeof nicEditor == "undefined") {
    loadWysiwygFile();
  } else {
    wysiwygReady();
  }
}
*/
