/*-------------------------[ comments ]------------------------------*/
function expandAllComments(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];
			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];

		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);
}

function addReplyForm(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 = 'http://'+siteTopDomain+'/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://cghub.com/login" id="login_link">Log in</a> or <a href="https://cghub.com/registration">Sign up</a> to add comment.</h4>';
	}
	
	if ($('form[@action="'+action+'"]').length == 0) {
		$('#comment_thread_'+parentCommentId).show();
		$('#comment_thread_'+parentCommentId).append(formHtml);
		$('form[@action="'+action+'"]').show();
		
		addWysiwygToTextarea(commentTextareaId);
		focusWysiwyg(commentTextareaId);
		//$('form[@action="'+action+'"] textarea').focus();
		
		setTimeout("onReadyTooltipSpan()", 500);
	} 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();
		focusWysiwyg(commentTextareaId);
		
	}
	
	return false;
}
function editCommentForm(link) {
	var attrs = $(link).attr('id').split('_');
	var commentId = attrs[1];
	
	var formHtml = $('#addCommentFormDiv').html();
	var action = 'http://'+siteTopDomain+'/comments/edit/'+commentId;
	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;
			editCommentAddForm(commentText, commentTextareaId, formHtml, action, commentId);
			
			$(link).find('img').attr('src', editImgSrc);
		}
	});
	
	return false;
}

function editCommentAddForm(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://cghub.com/login" id="login_link">Log in</a> or <a href="https://cghub.com/registration">Sign up</a> to edit comment.</h4>';
	}
	
	if ($('form[@action="'+action+'"]').length == 0) {
		//$('#comment_thread_'+parentCommentId).show();
		//$('#comment_thread_'+parentCommentId).append(formHtml);
		
		$('#editLink_'+commentId).parents('li.comment').append(formHtml);
		$('form[@action="'+action+'"]').show();
		
		addWysiwygToTextarea(commentTextareaId);
		focusWysiwyg(commentTextareaId);
		//$('form[@action="'+action+'"] textarea').focus();
		
		setTimeout("onReadyTooltipSpan()", 500);
	} else if($('form[@action="'+action+'"]').is(':visible'))  {
		$('form[@action="'+action+'"]').hide();
	} else {
		//$('#comment_thread_'+parentCommentId).show();
		$('form[@action="'+action+'"]').show();
		
		focusWysiwyg(commentTextareaId);
		
	}
}

function commentExpandCollapse(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')) {
		commentCollapseThread(model, parentId, parentCommentId, canDeleteComments);
	} else {
		commentExpandThread(model, parentId, parentCommentId, canDeleteComments);
	}
}

function commentExpandThread(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) {
//		console.log(thread);
//		console.log(thread.indexOf('div id="comment_'));
		$('#comment_thread_'+parentCommentId).show();
//		$('#comment_'+parentCommentId+' .reply_toggle').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
		$(link).find('img').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
		$(link).removeClass('closed').addClass('opened');
	} else {
		$(link).removeClass('closed').addClass('opened');
		
		var repliesCount = $(link).contents()[1].data.trim();
		var re = /([0-9]+)/;
		repliesCount = re.exec(repliesCount)[1];
		if (repliesCount == 0) {
			return;
		}
		
		var repliesImg = $(link).children('img');
		if ($(repliesImg).attr('src').indexOf('working2.gif') != -1) { //ajax working
			return;
		}
		$(repliesImg).attr('src', $(repliesImg).attr('src').replace('toggle/closed.gif', 'working2.gif'));
		
		$.get("/comments/expand/"+model+"/"+parentId+"/"+parentCommentId+'/1/'+canDeleteComments+'?call=ajax&rand='+Math.random(), function(response) {
			$(repliesImg).attr('src', $(repliesImg).attr('src').replace('working2.gif', 'toggle/open.gif'));
			
			if (response == 'empty') {
				return;
			}

			$('#comment_thread_'+parentCommentId).prepend(response);
			$('#comment_thread_'+parentCommentId).show();

			if (!onReadyUserpicTooltipInUse) {
				onReadyUserpicTooltipInUse = true;
				setTimeout("onReadyUserpicTooltip();onReadyUserpicTooltipInUse = false;", 5000);
			}
//			$('#comment_'+parentCommentId+' .reply_toggle').attr('src', $('#comment_'+parentCommentId+' .reply_toggle').attr('src').replace('closed', 'open'));
			
//			setTimeout("$('#comment_thread_"+parentCommentId+" .expandLink').each(expanLinkBind);", 200);
//			setTimeout("$('#comment_thread_"+parentCommentId+" .replyLink').each(replyLinkBind);", 400);
		});
	}

//	$(link).unbind('click');
//	$(link).bind('click', function() {
//		commentCollapseThread(link);return false;
//	});

}
function commentCollapseThread(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;
//	});
}
function getCommentPage(link) {
	var attrs = $(link).attr('id').split('_');
	var model = attrs[1];
	var parentId = attrs[2];
	var parentCommentId = attrs[3];
	var page = attrs[4];
	var canDeleteComments = attrs[5];

	$.get('/comments/expand/'+model+'/'+parentId+'/'+parentCommentId+'/'+page+'/'+canDeleteComments+'?call=ajax&rand='+Math.random(), function(response){
		$('#getCommentPageDiv_'+model+'_'+parentId+'_'+parentCommentId+'_'+page+'_'+canDeleteComments).replaceWith(response);
		
		if (!onReadyUserpicTooltipInUse) {
			onReadyUserpicTooltipInUse = true;
			setTimeout("onReadyUserpicTooltip();onReadyUserpicTooltipInUse = false;", 2000);
		}
	});
}
function commentPreview(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);
}

/*-------------------------------------------------[ wysiwyg ]--------------------------------------*/
var wysiwygEditors = new Array();
var wysiwygFramesIds = new Array();

/**
 * @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();
	}
}
*/
function addWysiwygToTextarea(textareaId) {
	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);
}
function focusWysiwyg(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();
	}
}