/**********************************
*
*  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 = $(opt.form).remove().css('display','block').children(opt.counter).val(defaults.maxText).parents(opt.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 );
			
			if( $(this).hasClass(opt.reply) )
			{
				var parent = $(this).parents(opt.commentbox);
				parent.append( form );
				$(opt.parent).val(parent.attr('id').match(/[0-9]+/));
				$(opt.title).val(parent.find('.author').text());
			}
			else
			{
				$(opt.mainBox).prepend( form );
			}			
		}
		else
		{
			alert( 'Трябва да сте логнат!' );
		}
		return false;
	});
	
	$(opt.cancel).live( 'click', function(){
		$(opt.form).removeForm( opt.text );
	});
	
	$(opt.hidenav).bind( 'click', function(){
		var $this = $(this),
			parent = $this.parents(opt.commentbox);

		if( parent.hasClass(opt.hide) )
		{
			parent.removeClass(opt.hide);
			$this.text('Скрий Коментара');
		}
		else
		{
			parent.addClass(opt.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();
			return false;
		}
		else if( $(opt.text).val().length < 1 )
		{
			alert('Трябва да въведете текст на коментара!');
			$(opt.text).focus();
			return false;
		}		
		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	
					{
						$(opt.form).submit();
						countSymbols();
					}
				},
				'text'
			);
		}
		else if( $(opt.text).val().length > 0 )
		{
			$(opt.form).submit();
			countSymbols();
		}		
		return false;
	});
	
	$(opt.nav + ' > div').live('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').match(/[0-9]+/);

			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( 'keydown', countSymbols ).live( 'keyup', countSymbols );	
		
	$(opt.gotoPage).keypress(function( event ){
		var code = event.which ? event.which : event.keyCode;
		if( code > 31 && (code < 48 || code > 57) )
			return false;
		return true;
	});
	
	$(opt.gotoBtn).click(function(){
		var val = $(this).siblings(opt.gotoPage).val(),
			max = $(opt.gotoMax).val(),
			url = $(this).siblings(opt.gotoUrl).val();
		
		if( val > 0 & val != '' )
		{
			val = Number( val ) > Number( max ) ? max : val;
			window.location = 'http://' + window.location.hostname + window.location.pathname + url.replace('{pagenum}',val);
		}
	});	
};

$.fn.removeForm = function( text )
{
	return this.each(function(){
		if( $(text).val().length > 0 )
		{
			if( !confirm('Въведения от Вас текст във формата за коментари ще бъде изгубен.') )
				window.location = window.location + "#comment-post"
			else
				$(this).remove().find('textarea').val('');
		}
		else
			$(this).remove().find('textarea').val('');
	});	
}

function countSymbols()
{
	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 ) )
	else
		$(defaults.counter).val( max - txt.length );
}

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',
	hide:				'comment-hide',
	gotoPage:			'.comments-goto-page',
	gotoBtn:			'.comments-goto-go',
	gotoUrl:			'.comments-goto-url',
	gotoMax:			'.comments-goto-max',
	gradeup:			'comments-grade-up',
	gradedown:			'comments-grade-down',
	userid:				0,
	maxAuthor:			20,
	maxText:			500,
	guestPost:			true,
	guestGrade:			true,
	authorMust:			false
};

})(jQuery);