/**********************************
*
*  Author: 		P. Belenski
*  Project: 	Comments Web Service ( CWS )
*  Filename: 	comments.js
*  Created on:	13.04.2009
*  Contents: 	Event handler
*  Requires:	jQuery 1.3 or greater
*
**********************************/

(function($) {

var root = '/ibgws/ibgws_comments/';

$.ibgws_comments = function( options )
{
	var opt = $.extend( {}, defaults, options ),
		cookieset = navigator.cookieEnabled,
		form = 	'<form id="comment-post" action="'+root+'engine/postComment.php" method="post"><a name="comment-post"></a>' + 
				( opt.userid != 0 ? '' :
					'<label for="comment-author">Автор:</label><br />' +
					'<input type="text" name="author" id="comment-author" /><br /><br />'	
				) +
				'<textarea rols="10" cols="20" name="text" id="comment-text"></textarea><br />' + 
				( opt.userid != 0 ? '' :
					'<img src="' + root + '/ibgws/ibgws_comments/validate/code.php" alt="" /><br />' +
					'<label for="comment-code">Код:</label><br />' +
					'<input type="text" id="comment-code" name="code" /><br /><br />'		   
				) +		   
				'<input type="submit" value="Добави" id="comment-submit" />&nbsp;&nbsp;<input type="button" value="Отказ" id="comment-cancel" />' +
				'<input type="text" id="comment-count" disabled="disabled" value="' + defaults.maxText + '" /> оставащи символа' +
				'<input type="hidden" name="parent" 	value="0" id="comment-parent" />' +
				'<input type="hidden" name="title" 		value=""  id="comment-title"  />' +
				'<input type="hidden" name="owner_id" 	value="'+ opt.ownerid 	+'" />' +
				'<input type="hidden" name="photo_id" 	value="'+ opt.photoid 	+'" />' +
				'<input type="hidden" name="album_id" 	value="'+ opt.albumid 	+'" />' +
				'<input type="hidden" name="avatar" 	value="'+ opt.avatar	+'" />' +
				'<input type="hidden" name="item" 		value="'+ opt.item 		+'" />' +
				'<input type="hidden" name="item_id" 	value="'+ opt.itemid 	+'" />' +
				'</form>';
	
	$(opt.newComment +', '+opt.reply).live( 'click', function(){
		if( opt.guestPost || opt.userid != 0 )
		{
			if( $(opt.form).attr('id') != undefined )
				$(opt.form).removeForm( opt.text );
			else
			{
				if( $(this).hasClass(opt.reply) )
				{
					var parent = $(this).parents(opt.commentbox);
					parent.append( form );
					parent.find(opt.text).bind('keydown', countSymbols);
					parent.find(opt.text).blur(countSymbols);
					$(opt.parent).val(parent.attr('id').replace(opt.prefix,''));
					$(opt.title).val(parent.find('.author').text());
				}
				else
				{
					$(opt.mainBox).prepend( form );
					$(opt.mainBox).find(opt.text).bind('keydown', countSymbols);
					$(opt.mainBox).find(opt.text).blur(countSymbols);
				}
			}
		}
		else
		{
			alert( 'Трябва да сте логнат!' );
		}
		return false;
	});
	
	$(opt.cancel).live( 'click', function(){
		$(opt.form).removeForm( opt.text );
	});
	
	$(opt.hidenav).bind( 'click', function(){
		var $this = $(this);
		$this.parents('.comment-box')
			 .children('.comment-user-details, .comment-text, .comment-nav-frame')
			 .each(function(){
				if( $(this).hasClass('comment-hide') )
				{
					$(this).removeClass('comment-hide');
					$this.text('Скрий Коментара');
				}
				else
				{
					$(this).addClass('comment-hide');
					$this.text('Покажи Коментара');
				}
			}
		);
		return false;
	}); 
	
	$(opt.delcomment).bind('click',function(){
		var parent = $(this).parents('.comment-box'),
			_id = parent.attr('id').match(/[0-9]+/);
		if( confirm( 'Наистина ли искате да изтриете този коментар?' ) )
		{
			$.post(
				root + 'engine/delComment.php',
				{ id: _id, item: opt.item, itemid: opt.itemid },
				function()
				{
					window.location.reload();
				}
			);
		}
		return false;
	});
	
	$(opt.submit).live( 'click', function(){
		if( opt.authorMust && $(opt.author).val().length < 1 &&  opt.userid == 0  )
		{
			alert('Трябва да въведете автор!');
			$(opt.author).focus();
		}
		else if( $(opt.text).val().length < 1 )
		{
			alert('Трябва да въведете текст на коментара!');
			$(opt.text).focus();
		}
		
		if( opt.userid == 0 )
		{
			$.post(
				root + 'validate/validate.php',
				{ code: $(opt.code).val() },
				function( responce )
				{
					if( responce == 0 )
					{
						alert('Грешен код!');
						$(opt.code).val('');
						$(opt.code).focus();
					}
					else	
					{
						countSymbols();
						$(opt.form).submit();
					}
				},
				'text'
			);
		}
		else if( $(opt.text).val().length > 0 )
		{
			countSymbols();
			$(opt.form).submit();
		}
		
		return false;
	});
	
	$(opt.nav + ' > div').bind('click', function(){
		var parent = $(this).parent();
		
		if( parent.hasClass('grade') && cookieset && ( opt.guestGrade || opt.userid != 0 ) )
		{
			var grade 	= $(this).hasClass(opt.gradeup) ? 1 : -1,
				span 	= $(this).siblings('.comments-grade'),
				numPos 	= $(this).siblings('.comments-num').children('.comments-positive-num'),
				numNeg 	= $(this).siblings('.comments-num').children('.comments-negative-num'),
				comment = $(this).parents(opt.commentbox).attr('id').replace(opt.prefix,'');

			parent.removeClass('grade');
			
			$.post(
				root + 'engine/gradeComments.php',
				{ 
					grade: 		grade,
					site:		opt.site,
					item:		opt.item,
					itemid: 	opt.itemid,
					page: 		opt.page,
					usersite: 	opt.usersite,
					userid: 	opt.userid,
					commentid: 	comment
				},
				function( responce )
				{
					if( grade > 0 )
					{
						numPos.html( Number( numPos.text() ) + 1 );
					}
					else
					{
						numNeg.html( Number( numNeg.text() ) + 1 );
					}
					
					span.html( Number( span.text() ) + grade );
					span.text() == '' ? span.html('0') : span.text() ;
					
					if( span.text() > 0 )
					{
						span.css( 'color', 'green' ); 
						span.html( '+' + span.text() );
					}
					else if( span.text() < 0 )
					{
						span.css( 'color', 'red' );
						span.html( '&nbsp;' + span.text() );
					}
					else
					{
						span.css( 'color', 'grey' );
						span.html( '&nbsp;&nbsp;' + span.text() );
					}
				},
				'text'
			);	
		}
		else if( $(this).parent().hasClass('grade') )
		{
			alert('Трябва да се логнете, за да гласувате!');
		}
	});
	
	$('.'+opt.gradeup).add('.'+opt.gradedown).hover(
		function(){
			if( $(this).hasClass(opt.gradeup) )
				$(this).addClass('hover-up');
			else if( $(this).hasClass(opt.gradedown) )
				$(this).addClass('hover-down');
		},
		function(){
			if( $(this).hasClass(opt.gradeup) )
				$(this).removeClass('hover-up');
			else if( $(this).hasClass(opt.gradedown) )
				$(this).removeClass('hover-down');
		}
	);
	
	if( opt.userid == 0 && defaults.maxAuthor !=0 )
		$(opt.author).live( 'keydown', 'countSymbols' ).live( 'keyup', 'countSymbols' );
		
	if( defaults.maxText !=0 )	
	{
		//$(opt.text).live( 'keyup', countSymbols );//.live( 'keydown', 'countSymbols' );	
	}
};

$.fn.removeForm = function( text )
{
	return this.each(function(){
		if( $(text).val().length > 0 )
		{
			if( !confirm('Има отворена форма с текст!') )
				window.location = window.location + "#comment-post"
			else
				$(this).remove();
		}
		else
			$(this).remove();
	});	
}

function countSymbols(e)
{
	var counter = $(defaults.counter).val(),
		txt = $(this).val(), max;
		
	if( $(this).attr('id') == defaults.author.replace('#','') )
		max = defaults.maxAuthor;
	else
		max = defaults.maxText;

	if( txt.length > max )
	{
		$(this).val( txt.substr( 0, max ) )
		return false;
	}
	else
	{
		$(defaults.counter).val( max - txt.length );
		return true;
	}
}

var defaults = 
{
	mainBox:			'#comments-cont',
	form:				'#comment-post',
	code:				'#comment-code',
	cancel:				'#comment-cancel',
	author:				'#comment-author',
	text:				'#comment-text',
	counter:			'#comment-count',
	submit:				'#comment-submit',
	title:				'#comment-title',
	parent:				'#comment-parent',
	hidenav:			'.comment-hide-nav',
	delcomment:			'.comment-delete',
	newComment: 		'.comment-new',
	reply: 				'.comment-reply',
	nav:				'.comment-nav',
	commentbox:			'.comment-box',
	prefix:				'comment-',
	gradeup:			'comments-grade-up',
	gradedown:			'comments-grade-down',
	userid:				0,
	maxAuthor:			20,
	maxText:			500,
	guestPost:			false,
	guestGrade:			false,
	authorMust:			false
};

})(jQuery);
