/**
 * Comments class
 * Gets comments and displays them, type can be: userImage, starImage, News
 * and id is the object's id 
 */
 var imageCommentsTemplate = 
'<div class="comentariu clearfix" id="{id}">'+
'<div class="title"><a href="{userurl}">{username}</a>{date_added}</div>'+
'<div class="img_container"><a href="{userurl}"><img src="{avatar}"/></a></div>'+
'<div class="comm">' +
'<div class="title_comm">{subject}</div>'+
'<p>{comment}</p>'+
'</div>' +
'</div>';

var imageCommentsFanclubTemplate = 
'<div class="comentariu clearfix" id="{id}">'+
'<div class="title"><a href="{userurl}">{username}</a>{date_added}</div>'+
'<span><a href="{userurl}"><img src="{avatar}"/></a></span>'+
'<p>{comment}</p>'+
'</div>';

var imageCommentsTemplateAdmin = 
'<div class="comentariu clearfix" id="{id}">'+
'<div class="title">'+
'<a href="{userurl}"><img src="{avatar}"/></a>'+
'<a href="{userurl}">{username}</a>{date_added}</div>'+
'<p class="comment">{comment}</p>'+
'<div>'+
	'<form action="#" class="edit_form clearfix">'+
		'<input type="hidden" name="commentId" value="{id}">'+
		'{commentApprove}'+
		'<input type="submit" value="Sterge" class="sterge commentDelete" size="10"/>'+
	'</form>'+
'</div>'+
'</div>';

 var newsCommentsTemplate = 
'<div id="{id}" class="comentariu clearfix {hidden}">'+
'<div class="title">'+
'<a href="{userurl}"><img src="{avatar}"/></a>'+
'<a href="{userurl}">{username}</a>{date_added}</div>'+
'<p class="subject"><a href="#">{subject}</a> <a href="#" class="up"></a> <a href="#" class="down"></a> (<label class="points">{points}</label> puncte)</p>'+
'<p class="comment">{comment}</p>'+
'</div>';

 var videoCommentsTemplate = 
'<div class="comentariu clearfix" id="{id}">'+
'<div class="title">'+
'<a href="{userurl}">{username}</a>{date_added}</div>'+
'<span><a href="{userurl}"><img src="{avatar}"/></a></span>'+
'<p>{comment}</p>'+
'</div>';

var Comments = 
{
	id : '1',
	type: 'userImage',
	divId: '#comments',
	pages:'.paginare',
	page: '1',
	nrPages: '1',
	template : newsCommentsTemplate,
	init: function()
	{	
			this.pagination();
			this.bind();
	},
	bind: function()
	{
		$(this.divId + ' .subject > a:first-child').bind('click', function (e) 
		{
			//console.log('img');

			$(this.parentNode.parentNode).slideUp("slow",function() 
			{	
				$(this).toggleClass('hidden');
				//console.log('here')
				//console.log(this);
				$(this).slideDown("slow");}
			);
			return false;
		});

		$(this.divId + ' .subject .up').bind('click', function (e) 
		{

			//console.log('bind up ');
			//console.log(this);
			//console.log(this.parentNode);
			//console.log(this.parentNode.parentNode);
			//console.log('id = ' + this.parentNode.parentNode.id);

			var points = $('.points',this.parentNode);
			var nrPoints = parseInt(points.html()) + 1;//add one point
			nrPoints += '';//convert to string	
			$.get("/?module=Ajax&action=addCommentsVotes&type=" + Comments.type + "&objectId=" + this.parentNode.parentNode.id  + "&vote=1", 
			function( data )
			{ 
				if(data == '1' )
				{
					points.html( nrPoints );
				}
				else
				if(data == '-1')
				{
					$('#commentsMessage').html("Ai votat deja!").show();
				}
				else
				{
					$('#commentsMessage').html("Nu esti autentificat!").show();
				}
				return true;
			});
			return false;
		});

		$(this.divId + ' .subject .down').bind('click', function (e) 
		{
			var points = $('.points',this.parentNode);
			var nrPoints = parseInt(points.html()) - 1;//substract one point
			nrPoints += '';//convert to string
			$.get("/?module=Ajax&action=addCommentsVotes&type=" + Comments.type + "&objectId=" + this.parentNode.parentNode.id  + "&vote=-1", 
			function( data )
			{  
				if(data == '1' )
				{
					points.html( nrPoints );
				}
				else if(data == '-1')
				{
					$('#commentsMessage').html("Ai votat deja!").show();
				}
				else
				{
					$('#commentsMessage').html("Nu esti autentificat!").show();
				}
				return true;
			});
			return false;
		});

		$('#addComment').unbind('submit');
		$('#addComment').bind('submit', function (e) 
		{
//console.log("/?module=Ajax&action=addComment&type=" + Comments.type + "&objectId=" + Comments.id);
			$.ajax({type:"POST",
					url: "/?module=Ajax&action=addComment&type=" + Comments.type + "&objectId=" + Comments.id,
					data: "subject=" + $('#subject').val()+ "&name=" + $('#name').val() + "&email=" + $('#email').val()+ "&comment=" + $('#comment').val(),
					success: function(msg){
						if(msg == '1')  
						{
							$('#comment').get(0).value = '';
							$('#commentsMessage').html("Comentariul a fost adaugat!").show();
							Comments.get( Comments.page );
						}
						else if (msg == '-1')
						{
							$('#commentsMessage').html("Nu esti autentificat!").show();
						}
						else if (msg == '-2')
						{
							$('#commentsMessage').html("Nu ai completat campul comentarii!").show();
						}
						else  
						{
							$('#commentsMessage').html("Eroare salvare comentariu :(").show();
						}
						return true;
					},
					error: function(msg)
					{
						$('#commentsMessage').html("Eroare salvare comentariu :(").show();
						return true;
					}
			});
			return false;
		
		});

		$('.commentApprove').bind('click', function (e) 
		{
			
			$.ajax({		type:"POST",
							url: "/?module=Ajax&action=approveComment&type=" + Comments.type + "&objectId=" + Comments.id,
							data: "commentId=" + $(this).siblings().filter(':hidden:first').get(0).value,
							success: function(msg){
								if(msg == '1')
								{
									$('#commentsMessage').html("Comentariul a fost aprobat!").show();
									Comments.get( Comments.page );
								}
								else  
								{
									$('#commentsMessage').html("Eroare la aprobare comentariu!").show();
								}
								return true;
							},
							error: function(msg)
							{
								$('#commentsMessage').html("Eroare la aprobare comentariu!").show();
								return true;
							}
					 });
			return false;
		});

		$('.commentDelete').bind('click', function (e) 
		{
			$.ajax({		type:"POST",
							url: "/?module=Ajax&action=delComment&type=" + Comments.type + "&objectId=" + Comments.id,
							data: "commentId=" + $(this).siblings().filter(':hidden:first').get(0).value,
							success: function(msg){
								if(msg == '1')  
								{
									$('#commentsMessage').html("Comentariul a fost sters!").show();
									Comments.get( Comments.page );
								}
								else  
								{
									$('#commentsMessage').html("Eroare stergere comentariu!").show();
								}
								return true;
							},
							error: function(msg)
							{
								$('#commentsMessage').html("Eroare stergere comentariu!").show();
								return true;
							}
					 });
			return false;
		})
	},
		

	get : function( page )
	{	
		this.page = page;
		//show loading 
		$( this.divId ).html( '<div style="padding:2em;text-align:center;width:auto;"><img src="/images/loading.gif"></div>' );
		$(Comments.divId).slideUp("slow");

	$.ajax({
	  url: '/',
	  cache: true,
	  data: "module=Ajax&action=getComments&type=" + this.type + "&objectId=" + this.id + "&page=" + page,
	  error:function (data, textStatus)
	  {
		$(Comments.divId).html('<div style="text-align:center;width:auto;padding:2em;"><h3>Eroare incarcare comentarii!</h3></div>');
		$(Comments.divId).slideDown();
	  },
	  type:"GET",
	  success:function( data, textStatus )
		{
			//clear comments div
			$( Comments.divId ).html("");
			var content = '';
		    var comments = eval( "(" + data + ")");	
			if (comments['comments'] != null && comments['commentsNr'] > 0 )
			{

			//add each comment, replacing the data in the template
			  $.each( comments['comments'] , function( i, item )
			  {
				
				var comment = Comments.template;
				for ( key in item )//get key => value
				{	
					comment = comment.replace(new RegExp( '{'+ key + '}', "g" ),item[key]);
				}

				if (item['points'] < 0) 
				{
					comment = comment.replace('{hidden}','hidden'); 
				}
				else 
				{
					comment = comment.replace('{hidden}','');
				}
				
				content += comment;
			  });
			} else
			{
				content = '<div style="text-align:center;width:auto;padding:1em;background:#eee;"><h3>Nici un comentariu!</h3></div>';
			}
			
			if (comments['commentsNr'] != null)
			{
				//set number of pages
				Comments.nrPages = comments['commentsNr'];
			}

//			$(Comments.divId).stop();//stop the slideup animation, usefull if the request is server faster than the animation completion
//			$(Comments.divId).css("height","auto");//if the animation was stoped, show comments directly, without slidedown animation
			$(Comments.divId).html(content);
			$(Comments.divId).slideDown("slow");
			Comments.bind();

			//redraw pagination
			Comments.pagination();
        }});
	},
	pagination : function()
	{

		//console.log('pg nr' + this.nrPages);

		//if only one page then hide pagination 
		if ( this.nrPages <= 1)
		{
			$(this.pages).html("");
			return true;
		}
		
		//doing it the old way (innerHTML) because there are to many nodes to create and it's slower
		
		//prev link
		if ( this.page > 1 )
		{
			//enabled, can click previous
			var pagination = '<a href="#" onclick="Comments.prev();return false;"><img src="/img/arrow4.gif" border="0" alt=""></a>';
		}
		else
		{
			//disabled, can't click previous
			var pagination = '<a href="#" onclick="Comments.prev();return false;"><img src="/img/arrow.gif" border="0" alt=""></a>';
		}
		
		//calculate from what number to start and to what number to stop to always have 10 links on the page (if there are at least 10 images) 
		if (this.nrPages <= 10)
		{
			var from = 1;
			var to = Math.min( 10, this.nrPages );
		} else
		if ( this.page + 5 > this.nrPages )
		{
			var from = this.nrPages - 9;
			var to = this.nrPages;
		} else
		if ( this.page > 5 )
		{
			var from = this.page - 4;
			var to = Math.min( this.page + 5, this.nrPages );
		} 
		else 
		{
			var from = 1;
			var to = Math.min( 10, this.nrPages );
		}

		//link to first page
		pagination += '<a href="#" class="pages" onclick="Comments.get(1);return false;">1</a>..';
		
		//generate links
		for ( var i = from; i <= to; i++ )
		{
			if ( i > 1)
			{
				pagination += '/';
			}
			//page links
			if ( i == this.page )
			{
				pagination += '<a href="#" id="page'+ i +'" class="page_selected" onclick="Comments.get('+ i +');return false;">'+ i +'</a>';	
			} else
			{
				pagination += '<a href="#" id="page'+ i +'" onclick="Comments.get('+ i +');return false;">'+ i +'</a>';
			}
		}
		
		//link to last page
		pagination += '..<a href="#" class="pages" onclick="Comments.get(' + this.nrPages + ');return false;">' + this.nrPages + '</a>';

		//next link
		if ( this.page < this.nrPages )
		{
			//enabled, can click next
			pagination += '<a href="#" onclick="Comments.next();return false;"><img src="/img/arrow2.gif" alt="" border="0"></a>';
		} else
		{
			//disabled, can't click next
			pagination += '<a href="#" onclick="Comments.next();return false;"><img src="/img/arrow1.gif" alt="" border="0"></a>';
		}
		
		//insert pagination html
		$(this.pages).html( pagination );
	},	
	next: function()
	{
		if ( this.page < this.nrPages )
		{
			this.page++;
			this.get( this.page );
		}

	},
	prev: function()
	{
		if ( this.page > 1 )
		{
			this.page--;
			this.get( this.page ) ;
		}
	}
}