/*
 * jQuery comments tree v1.0.0 - http://www.onlinetvcast.com/
 *
 * Copyright (c) 2010 Valery Nayda
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */
 
 (function($) {
 	$.comments = function(options) {
        var defaults = {
        	collapseNodeAll: 	'collapseNodeAll',
        	expandNodeAll: 		'expandNodeAll',
        	toggleCommentForm:	'toggleCommentForm',
        	addComment: 		'addComment',
        	goToParentComment:	'goToParentComment',
        	goToChildComment: 	'goToChildComment',
        	preview : 		 	'preview',
        	hideCommentForm:	'hideCommentForm',
        	editable:			false,			
        	
        	url: {
				add: 			'',			
				responce:  		'', 
				preview: 		'',
				edit: 			''
			},			        	        	
        	img: {
				path: 			'/js/my/comments/images/',			
				openName:  		'open.gif', 
				closeName: 		'close.gif'
			},
			classes: {
				visible: 		'_visible',
				hidden:  		'_hidden',			
				openImg:  		'_open',			
				closeImg:  		'_close'			
			}
        };
        var options = $.extend(defaults, options);
                                
        this.init = function(){		
			this.make();
			this.aCommentNew = [];
			this.iCurrentShowFormComment = 0;	
			this.iCommentIdLastView = null;	
			this.countNewComment = 0;
			this.hideCommentForm(this.iCurrentShowFormComment);
									
			var thisObj = this;
        	$('.' + options.collapseNodeAll).live('click', function(){
        		thisObj.collapseNodeAll();
        		return false;
        	}).bind('focus', function(){
        		$(this).blur();
        	});
        	        	
        	$('.' + options.expandNodeAll).live('click', function(){
        		thisObj.expandNodeAll();
        		return false;
        	}).bind('focus', function(){
        		$(this).blur();
        	});
        	
        	$('.' + options.toggleCommentForm).live('click', function(){
        		var id = $(this).attr('id').split('_');
        		thisObj.toggleCommentForm(id[1]);
        		return false;
        	});
        	
        	$('.' + options.addComment).live('click', function(){
        		var id = $(this).attr('id').split('_');
        		thisObj.addComment('form_comment', id[1]);
        		return false;
        	});
        	
        	$('.' + options.goToParentComment).live('click', function(){
        		thisObj.goToParentComment($(this));
        		return false;
        	});
        	
        	$('.' + options.goToChildComment).live('click', function(){
        		thisObj.goToChildComment($(this));
        		return false;
        	});
        	        	
        	$('.' + options.preview).live('click', function(){
        		thisObj.preview($('#form_comment_reply').val());
        		return false;
        	});
        	        	
        	$('.' + options.hideCommentForm).live('click', function(){
        		thisObj.hideCommentForm(thisObj.iCurrentShowFormComment);
        		return false;
        	});
        	
        	$('#form_comment').bind('submit', function(){
        		return false;
        	});
        	
        	if (options.editable) {
        		// edit in place
            	$('.edit').editable(options.url.edit, { 
                    type      : 'textarea',
                    cancel    : 'Cancel',
                    submit    : 'OK',
                    indicator : '<img src="/js/my/comments/images/loader.gif" alt="loading">',
                    tooltip   : 'Click to edit...'
                });
        	}	
		},
						
		this.make = function(){
			var thisObj = this;
			var aImgFolding = $('img.folding');
			aImgFolding.each(function(i){
				var img = $(this);
				var divComment = $(img.parents('div.comment').find('div.comment-children')[0]);
				if (divComment.size() && divComment.find('div.comment').size()) {
					thisObj.makeImg(img);
				} else {
					img.hide();
				}
			});		
		},
								
		this.makeImg = function(img) {
			var thisObj = this;
			img.css('cursor', 'pointer');
			img.css('display','inline');
			img.addClass(options.classes.closeImg);
			img.unbind('click');
			img.bind('click', function(){
				thisObj.toggleNode(img);		
			});
		},
		
		this.toggleNode = function(img) {	
			var b = img.hasClass(options.classes.closeImg);		
			if (b) {				
				this.collapseNode(img);
			} else {					
				this.expandNode(img);
			}
		},
		
		this.expandNode = function(img) {
			img.attr({'src': options.img.path + options.img.closeName});
			img.removeClass(options.classes.openImg);
			img.addClass(options.classes.closeImg);
				  
			var divComment = $(img.parents('div').find('div.comment-children')[0]);		
			divComment.removeClass(options.classes.hidden);
			divComment.addClass(options.classes.visible);		
		},
										
		this.collapseNode = function(img) {
			img.attr({'src': options.img.path + options.img.openName});
			img.removeClass(options.classes.closeImg);
			img.addClass(options.classes.openImg);
								    
			var divComment = $(img.parents('div').find('div.comment-children')[0]);		
			divComment.removeClass(options.classes.visible);
			divComment.addClass(options.classes.hidden);		
		},
		
		this.expandNodeAll = function() {
			var thisObj = this;
			var aImgFolding = $('img.' + options.classes.openImg);		
			aImgFolding.each(function(i){
				thisObj.expandNode($(this));
			});
		},
						
		this.collapseNodeAll = function() {
			var thisObj = this;
			var aImgFolding = $('img.' + options.classes.closeImg);		
			aImgFolding.each(function(i){
				thisObj.collapseNode($(this));
			});
		},
				
		this.scrollToComment = function(idComment) {
			var cmt = $('#comment_content_id_'+idComment);
			var deltaY = cmt.height()/2 - $(window).height()/2;
			if (deltaY > 0) {
	 			deltaY=0;
	 		}
			
	 		// elastic scrollTo
			this.scrollTo(0, cmt.offset()['top']+deltaY);
						
			if (this.iCommentIdLastView) {
				$('#comment_content_id_' + this.iCommentIdLastView).removeClass('view');
			}				
			$('#comment_content_id_' + idComment).addClass('view');
			this.iCommentIdLastView = idComment;
		},
				
		this.addComment = function(formObj, topicId) {
			var thisObj = this;
			formObj = $('#' + formObj);
			$.ajax({
				url : options.url.add,
				type : "POST",
				dataType : 'json',
				timeout : 30000,
				error : function() {
					this.ajaxError();
				},
				success : function(result) {
					if (! result) {
	            		thisObj.enableCommentForm();
	            		thisObj.ajaxError();
	        		}      
	        		if (result.error) {        			
						thisObj.enableCommentForm();
						thisObj.ajaxError(result.error);        			
	        		} else { 
	        			$('#form_comment_text').val('').disabled = true;
	        			thisObj.responseNewComment(topicId, $('#update-comments'), result.id, true);        			   								
	        		}
				},
				// Parametrs
				data : { 'request' : formObj.serialize() }
			});
	      	$('#form_comment_text').addClass('loader');		
		},
		
		this.responseNewComment = function(idTopic, objImg, selfIdComment, bNotFlushNew) {
			var thisObj = this;
			
			if (! bNotFlushNew) {
				var aDivComments = $('.comment');
				aDivComments.each(function(i){
					var item = $(this);
					var divContent = $(item.find('div.content')[0]);
					if (divContent.size()) {
						divContent.removeClass('new');
						divContent.removeClass('view');
					}
				});
			}
									
			var idCommentLast = thisObj.idCommentLast;
			objImg = $(objImg);
			objImg.attr('src', '/images/update_act.gif');
			$.ajax({
				url : options.url.responce,
				type : "POST",
				dataType : 'json',
				timeout : 30000,
				error : function() {
					this.ajaxError();
				},
				success : function(result) {
					objImg.attr('src', '/images/update.gif');
	            	if (!result) {
	                	thisObj.ajaxError();
	        		}
	        		if (result.error) {
	        			thisObj.ajaxError(result.error);
	        		} else {
	        			var aCmt = $(result.aComments);         			
	        			if (aCmt.size() > 0 && result.iMaxIdComment) {
	        				thisObj.setIdCommentLast(result.iMaxIdComment);
	        				var countComments = $('#count-comments');
	        				countComments.text(parseInt(countComments.text()) + aCmt.length);
	        			}
	        			var iCountOld = 0;
	        			if (bNotFlushNew) {		      	       			       			
	        				iCountOld = thisObj.countNewComment;        				
	        			} else {
	        				thisObj.aCommentNew=[];
	        			}
	        			if (selfIdComment) {
	        				thisObj.setCountNewComment(aCmt.length-1+iCountOld);
	        				thisObj.hideCommentForm(thisObj.iCurrentShowFormComment); 
	        			} else {
	        				thisObj.setCountNewComment(aCmt.length+iCountOld);
	        			}
	        			aCmt.each(function(i, item) {
	        				// item not jquery object
	        				if (! (selfIdComment && selfIdComment == item.id)) {
	        					this.aCommentNew = $.extend(this.aCommentNew, [item.id]);
	        				}
	        				thisObj.injectComment(item.idParent, item.id, item.html);
	        			}); 
	        			if (selfIdComment && $('comment_id_'+selfIdComment)) {
							thisObj.scrollToComment(selfIdComment);
						}
	        		}
				},
				// Parametrs
				data : { idCommentLast: idCommentLast, idTopic: idTopic }
			});
		},
		
		this.setCountNewComment = function(count) {
			this.countNewComment = count;		
			var divCountNew = $('#new-comments');
	        if (this.countNewComment > 0) {
	        	divCountNew.text(this.countNewComment); 
	        	divCountNew.css('display','block');        	
	        } else {
	        	this.countNewComment = 0;
	        	divCountNew.text(0);         	
	        	divCountNew.css('display','none');
	        }
		},
						
		this.injectComment = function(idCommentParent, idComment, sHtml) {		
			var newComment = $('<div>').attr({'class':'comment', 'id': 'comment_id_' + idComment});
			newComment.html(sHtml);
			if (idCommentParent) {
				this.expandNodeAll();	
				var divChildren = $('#comment-children-' + idCommentParent);		
				var imgParent = $(divChildren.parents('div').find('img.folding')[0]);		
				this.makeImg(imgParent);
				divChildren.append(newComment);
			} else {
				var divChildren = $('#comment-children-0');
				newComment.before(divChildren);
			}	
		},
		
		this.enableCommentForm = function() {
			$('#form_comment_text').removeClass('loader');
			$('#form_comment_text').disabled = false; 
		},
				
        this.toggleCommentForm = function(idComment) {
			if (! $('#reply_' + this.iCurrentShowFormComment).size() || ! $('#reply_' + idComment).size()) {
				return;
			} 
			divCurrentForm = $('#reply_' + this.iCurrentShowFormComment);
			divNextForm = $('#reply_' + idComment);
								
			var slideCurrentForm = divCurrentForm;
			var slideNextForm = divNextForm;
			
			$('#comment_preview_' + this.iCurrentShowFormComment).html('').css('display','none');
			if (this.iCurrentShowFormComment == idComment) {
				slideCurrentForm.toggle();
				//$('form_comment_text').focus();
				return;
			}
						
			slideCurrentForm.slideUp();
			divNextForm.html(divCurrentForm.html());
			divCurrentForm.html('');		
			divNextForm.css('display','block');
			slideNextForm.hide();
			
			slideNextForm.slideDown();
					
			//$('form_comment_text').focus();
			$('#form_comment_text').attr('value','');
			$('#form_comment_reply').attr('value',idComment);
			this.iCurrentShowFormComment = idComment;
		},
						
		this.hideCommentForm = function(idComment) {
			if ($('#reply_' + idComment).size()) {
				this.enableCommentForm();
				$('#comment_preview_' + this.iCurrentShowFormComment).html('').css('display','none');
				$('#reply_' + idComment).hide();
			}
		},
				
		this.preview = function(obj) {
			var thisObj = this;
			var text = $('#form_comment_text').val();
			$.ajax({
				url : options.url.preview,
				type : "POST",
				dataType : 'json',
				timeout : 30000,
				error : function() {
					this.ajaxError();
				},
				success : function(result) {
					if (! result) {
		                thisObj.enableCommentForm();
	            		thisObj.ajaxError();
		        	}
		            if (result.error) {
		            	thisObj.enableCommentForm();
						thisObj.ajaxError(result.error);
		            } else {
		            	var divPreview = $('#comment_preview_' + thisObj.iCurrentShowFormComment);
		            	if (divPreview.size() == 0) {
		            		divPreview = $('#text_preview');
		            	}
		            	if (divPreview.size()) {
		            		divPreview.html(result.text).show();
		            	}
		            }
				},
				// Parametrs
				data : { 'text' : text }
			});
		},
				
		this.goToParentComment = function(obj) {
			// TODO:			
			return false;
		},
		
		this.goToChildComment = function(obj) {
			// TODO:
			return false;
		}
		
		this.toggleComment = function(obj,commentId) {
			// TODO:
			return false;
		},
		
		this.scrollTo = function(x, y) {
			$("html").animate({ scrollLeft: x, scrollTop: y}, 700);
		},
				
		this.ajaxError = function(message) {
			if ($(message).size() == 0) {
				message = 'Please try again later';
			}
			showGrowl(message, 'error');
		},
		
		this.setIdCommentLast = function(id) {
			this.idCommentLast = id;
		}
		
		this.init();
        var self = this;
		return this;
    };
 })(jQuery);
